I want to log errors on try catch construct using log4js. I have next code:
let log4js = require('log4js')
log4js.configure({
appenders: {
asterisk: {type: 'file', filename: 'filename'},
out: {type: 'stdout'},
},
categories: {default: {appenders: ['asterisk', 'out'], level: 'all'}}
})
const logger = log4js.getLogger('asterisk')
async function myFunc() {
try {
let tmp = await someFunc()
}
catch (err) {
logger.error(err)
process.exit(1)
}
}
myFunc()
When an error occurs, I see it in the console, but it is not written to the file. If I use logger outside try..catch block then everything works fine. What could be the problem?
As suggested to me on GitHub, the problem is in the process.exit - this causes node to exit before the logger.error call (which is asynchronous behind the scenes) has written to the file. Right code will be like this:
and it works fine.