[英]log4js for Node doesn't output to file, only to console
我需要一個log4js
應用程序的基本日志系統,所以我正在用log4js
做一些測試,這似乎是這些情況的標准。 我需要將消息打印到控制台和文件,因此我編寫了以下代碼:
// Logger
var log4js = require('log4js');
log4js.configure({
appenders: {
'console': { type: 'console' },
'file': { type: 'file', filename: 'logs/mailer.log' }
},
categories: {
default: { appenders: ['file', 'console'], level: 'DEBUG' },
}
});
var logger = log4js.getLogger("Mailer");
logger.info("Starting application");
try {
// CODE TO READ APP CONFIG FILE
}
catch(e) {
logger.error("Couldn't read app configuration file (config.yml)");
// This is the trouble maker. It kills the app without flushing the logs
process.exit(1);
}
當我運行應用程序時,日志顯示如下:
[2019-07-29T16:07:24.763] [INFO] Mailer - Starting application
問題是我可以在控制台中看到消息,但日志文件仍然是空的。 如果我刪除它並再次運行應用程序,它就會被創建,所以我認為問題是缺少選項或類似的東西。
有什么建議嗎?
為了避免更改應用程序邏輯和所有process.exit()
調用,我已將file
附加程序替換為其同步版本fileSync
,現在一切都按預期工作。 所以,我唯一改變的是我聲明“文件”附加程序的行:
'file': { type: 'fileSync', filename: 'logs/mailer.log' }
干杯!
您可以使用 loggerWinston...我在我的 nodejs 應用程序中使用它並且它工作正常。
您應該將它添加到 server.js(用於啟動節點的文件)中
const winston = require('winston');
const tsFormat = () => (new Date()).toLocaleTimeString();
global.loggerWinston = new (winston.Logger)({
transports: [
// colorize the output to the console
new (winston.transports.Console)({
timestamp: tsFormat,
colorize: true,
level: 'debug'
}),
new (winston.transports.File)({
filename: 'results.log',
timestamp: tsFormat,
// level: (process.env.NODE_ENV || 'development') === 'development' ? 'debug' : 'info'
level: 'info'
})
]
});
results.log 文件應添加到您的項目文件夾中。
這是參考https://www.npmjs.com/package/winston
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.