当我创建一个 nodejs winston 控制台记录器并设置 json:true
时,它总是以多行格式输出 JSON 日志。如果我将这些通过管道传输到一个文件并尝试 grep 该文件,我的 grep 命中仅包含日志行的一部分。我希望 winston 以 JSON 格式输出我的日志行,而不是漂亮地打印 JSON
这是我的配置( CoffeeScript ,抱歉):
winston = require 'winston'
logger = new (winston.Logger)(
transports: [
new winston.transports.Console({
json: true
})
]
)
还有一些示例输出:
{
"name": "User4",
"level": "info",
"message": "multi line whyyyyy"
}
最佳答案
winston 3.x(当前版本)
默认格式化程序
const winston = require('winston');
const logger = winston.createLogger({
format: winston.format.json(),
transports: [
new winston.transports.Console()
]
});
例子
const test = { t: 'test', array: [1, 2, 3] };
logger.info('your message', test);
// logger output:
// {"t":"test","array":[1,2,3],"level":"info","message":"your message"}
自定义格式化程序
const winston = require('winston');
const { splat, combine, timestamp, printf } = winston.format;
// meta param is ensured by splat()
const myFormat = printf(({ timestamp, level, message, meta }) => {
return `${timestamp};${level};${message};${meta? JSON.stringify(meta) : ''}`;
});
const logger = winston.createLogger({
format: combine(
timestamp(),
splat(),
myFormat
),
transports: [
new winston.transports.Console()
]
});
例子:
const test = { t: 'test', array: [1, 2, 3] };
// NOTE: wrapping object name in `{...}` ensures that JSON.stringify will never
// return an empty string e.g. if `test = 0` you won't get any info if
// you pass `test` instead of `{ test }` to the logger.info(...)
logger.info('your message', { test });
// logger output:
// 2018-09-18T20:21:10.899Z;info;your message;{"test": {"t":"test","array":[1,2,3]}}
winston 2.x(旧版)
似乎已接受的答案已过时。以下是当前 winston 版本 (2.3.1) 的操作方法:
var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
json: true,
stringify: (obj) => JSON.stringify(obj),
})
]
})
注意 winston.transports.Console
周围的括号。
关于node.js - 如何将我的 Node winston JSON 输出更改为单行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32131287/