带有 ES 模块的 log4js 节点?

log4js-node with ES module?

我正在尝试在我的代码中设置 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 This file is being treated as an ES module because it has a '.js' file extension and 'package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

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

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

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

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

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

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

log4js.configure(appSettings.log4js.traceLogConfig);