我正在尝试使用Winston和winston-daily-rotate-file将来自node.js服务器的所有控制台/日志输出记录到一个文件中,该文件(希望)每天在午夜旋转。
我遇到的问题是未处理的异常似乎会生成一个新的日志文件,而不是写入现有的日志文件。有关复制行为,请参见下面的示例代码。如何将所有输出保存到单个日志文件以及输出到控制台?目前,控制台方面似乎还不错,但请随时指出我所缺少的明显之处。
操作系统:Win 10
节点:v12.16.0
npm:v6.13.4
温斯顿:v3.2.1
温斯顿每日旋转文件:v4.4.2
const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
const path = require('path');
var logger = new (winston.createLogger)({
transports: [
new (winston.transports.Console)({
format: winston.format.combine(
winston.format.timestamp(),
winston.format.colorize({ all: true }),
winston.format.printf((info) => {
const {
timestamp, level, message
} = info;
return `${timestamp} - ${level}: ${message}`;
}),
),
handleExceptions: true
}),
new DailyRotateFile({
name: 'file',
datePattern: 'YYYY-MM-DDTHH-mm-ss',
handleExceptions: true,
format: winston.format.combine(
winston.format.timestamp(),
winston.format.printf((info) => {
const {
timestamp, level, message
} = info;
return `${timestamp} - ${level}: ${message}`;
}),
),
filename: path.join(__dirname, 'logs', '%DATE%.log')
}),
]
});
logger.info("This is an info message");
logger.error("This is an error message");
setTimeout(() => {throw new Error('oh dear!')}, 5000);
最佳答案
我的问题是由datePattern选项引起的。 winston-daily-rotate-file使用此模式来确定文件旋转的频率。因为我在模式中包括了几秒钟,所以它正在寻找具有当前时间戳记的文件(精确到秒),并在写入文件之前创建它。
要获取每日文件,我只需要更改
datePattern: 'YYYY-MM-DDTHH-mm-ss'
至
datePattern: 'YYYY-MM-DD'
关于javascript - Winston javascript记录器正在创建两个单独的日志文件。如何将所有条目记录到单个文件中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60194788/