如何将节点winston JSON输出更改为单行

zay*_*uan 14 node.js winston

当我创建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
    })
  ]
)
Run Code Online (Sandbox Code Playgroud)

还有一些示例输出:

{
  "name": "User4",
  "level": "info",
  "message": "multi line whyyyyy"
}
Run Code Online (Sandbox Code Playgroud)

jma*_*eli 27

winston 3.x(当前版本)

默认格式化程序

const winston = require('winston');
const logger = winston.createLogger({
  format: winston.format.json(),
  transports: [
    new winston.transports.Console()
  ]
});
Run Code Online (Sandbox Code Playgroud)

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"}
Run Code Online (Sandbox Code Playgroud)

自定义格式化程序

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()
  ]
});
Run Code Online (Sandbox Code Playgroud)

例:

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]}}
Run Code Online (Sandbox Code Playgroud)

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),
    })
  ]
})
Run Code Online (Sandbox Code Playgroud)

注意括号周围winston.transports.Console.