【问题标题】:log4js-node with ES module?带有 ES 模块的 log4js-node?
【发布时间】:2021-08-13 13:09:22
【问题描述】:

我正在尝试在我的代码中设置 log4js-node。 由于我想从不同的 .js 文件写入同一个日志文件,因此我将其设置为外部文件per the documentation:

const appSettings = {
        log4js: {
            traceLogConfig: {
                appenders: {
                    fileAppender: { type: 'file', filename: `./logs/${settings.custid}/${Date.now()}.log`},
                    consoleAppender: { type: 'console' }
                },
                categories: {
                    default: { appenders: ['fileAppender', 'consoleAppender'], level: 'trace'}
                }
            }
        }
    };
    
    module.exports = appSettings;

在文件中:

import log4js from 'log4js';

//Setting up logger
const { traceLogConfig } = require('./logs').log4js;
log4js.configure(traceLogConfig);
const logger = log4js.getLogger();

但是,当我尝试运行代码时,我收到以下错误消息:

const { traceLogConfig } = require('./logs').log4js; ^

ReferenceError: require is not defined in ES module scope, you can use import instead 此文件被视为 ES 模块,因为它 有一个 '.js' 文件扩展名和 'package.json' 包含“类型”: “模块”。要将其视为 CommonJS 脚本,请将其重命名为使用 '.cjs' 文件扩展名。

我不知道如何将此结构 (const { traceLogConfig } = require('./logs').log4js;) 转换为 ES6 模块。 我试过了:

import {traceLogConfig} from './logs'.log4js
import {traceLogConfig} from './logs.log4js'
import {traceLogConfig} from './logs.js.log4js'

通常,visual studio code 会给我一个小灯,显示如何自动将其转换为 ES6 模块兼容代码,但这次没有显示。

【问题讨论】:

    标签: node.js import es6-modules log4js-node


    【解决方案1】:

    好的,我找到了答案。 您需要先像这样导入整个文件:

    import appSettings from '../logs.js';
    

    那你调用的时候需要参考具体的设置:

    log4js.configure(appSettings.log4js.traceLogConfig);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      • 2017-09-26
      • 2013-11-11
      • 2022-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多