我正在使用 Winston ^3.0.0-rc6,如下所示:
var options = {
file: {
level: 'info',
filename: `${appRoot}/logs/app.log`,
handleExceptions: true,
json: true,
prettyPrint: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: true,
}
};
const jsonFormatter = (logEntry) => {
if (logEntry.type) {
const base = {
timestamp: new Date()
};
const json = Object.assign(base, logEntry);
logEntry[MESSAGE] = JSON.stringify(json);
} else {
logEntry = "";
}
return logEntry;
}
const logger = winston.createLogger({
format: winston.format(jsonFormatter)(),
transports: [
new winston.transports.File(options.file)
],
exceptionHandlers: [
new winston.transports.File(options.uncaughtExceptions)
]
});
我的日志输出:
{"timestamp":"2018-06-10T07:41:03.387Z","type":"Authentication","status":"failed","level":"error","message":"Incorrect password"}
但我希望它们像:
{
"timestamp": "2018-06-10T07:41:03.387Z",
"type": "Authentication",
"status": "failed",
"level": "error",
"message": "Incorrect password"
}
我尝试使用 json: true 和 PrettyPrint 但它没有成功。
谁能帮忙
谢谢。
最佳答案
我在你的代码中注意到了这一点
logEntry[MESSAGE] = JSON.stringify(json);
您正在使用JSON.stringify()
它需要另外两个可选参数
JSON.stringify(value[, replacer[, space]])
如果您将 space
设置为您想要的空格数量,您将获得您正在寻找的输出。因此将初始行更改为:
logEntry[MESSAGE] = JSON.stringify(json, null, 2); // or 4 ;)
(replacer
参数为 null
,因为我们不想更改默认行为。)
关于json - winston 日志格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50781602/