I am trying to set up log4js-node in my code. As I want to write to the same log file from different .js files, I am setting it up in an external file as 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;
And in the files:
import log4js from 'log4js';
//Setting up logger
const { traceLogConfig } = require('./logs').log4js;
log4js.configure(traceLogConfig);
const logger = log4js.getLogger();
However, when I try to run the code, I get the following error message:
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.
I don't know how to convert this structure (const { traceLogConfig } = require('./logs').log4js;) to ES6 modules. I tried:
import {traceLogConfig} from './logs'.log4js
import {traceLogConfig} from './logs.log4js'
import {traceLogConfig} from './logs.js.log4js'
Usually, visual studio code gives me a small lamp that shows how to automatically convert it to ES6 module compatible code, but this time it doesn't show up.
Ok, I found the answer. You need to first import the whole file like this:
import appSettings from '../logs.js';
Then you need to reference the specific settings when you call it:
log4js.configure(appSettings.log4js.traceLogConfig);