【问题标题】:How do I change my node winston JSON output to be single line如何将我的节点 winston JSON 输出更改为单行
【发布时间】:2015-11-14 20:46:12
【问题描述】:

当我创建 nodejs winston 控制台记录器并设置 json:true 时,它总是以多行格式输出 JSON 日志。如果我将这些通过管道传输到一个文件并尝试 grep 该文件,我的 grep 命中仅包含日志行的一部分。我希望 winston 以 JSON 格式输出我的日志行,但不要漂亮地打印 JSON

这是我的配置(咖啡脚本,抱歉):

winston = require 'winston'
logger = new (winston.Logger)(
  transports: [
    new winston.transports.Console({
     json: true
    })
  ]
)

还有一些示例输出:

{
  "name": "User4",
  "level": "info",
  "message": "multi line whyyyyy"
}

【问题讨论】:

    标签: node.js winston


    【解决方案1】:

    winston 传输提供了一种覆盖 stringify 方法的方法,因此通过修改上面的配置,我得到了单行 JSON 输出。

    新配置:

    winston = require('winston')
    logger = new (winston.Logger)({
      transports: [
        new winston.transports.Console({
         json: true,
         stringify: (obj) => JSON.stringify(obj)
        })
      ]
    })
    

    【讨论】:

      【解决方案2】:

      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 周围的括号。

      【讨论】:

      • 我已将此作为公认的答案,但还没有机会进行测试。如果有人发现这不适用于指定的版本,请告诉我
      • 在控制台后指向左括号时出现错误:TypeError: (intermediate value) is not a function"winston": "^3.0.0-rc1"
      • 这在版本 ^3.0.0 中已弃用。
      • 我使用的是winston 2.x,它按预期工作
      【解决方案3】:

      "winston": "^3.0.0"

      function createAppLogger() {
        const { combine, timestamp, printf, colorize } = format;
      
        return createLogger({
          level: 'info',
          format: combine(
            colorize(),
            timestamp(),
            printf(info => {
              return `${info.timestamp} [${info.level}] : ${JSON.stringify(info.message)}`;
            })
          ),
          transports: [new transports.Console()]
        });
      }
      

      输出:

      2018-08-11T13:13:37.554Z [info] : {"data":{"hello":"Hello, World"}}

      【讨论】:

        【解决方案4】:
        winston.format.printf(
            info => `${info.timestamp} ${info.level}: ${JSON.stringify(info.message, null, 2)}`))
        

        将漂亮地打印 json 对象

        【讨论】:

          【解决方案5】:

          开启"winston": "^3.2.1"

          这对我很有用

          const {createLogger, format} = require('winston');
          
          // instantiate a new Winston Logger with the settings defined above
          var logger = createLogger({
          
              format: format.combine(
                format.timestamp(),
                // format.timestamp({format:'MM/DD/YYYY hh:mm:ss.SSS'}),
                format.json(),
                format.printf(info => {
                  return `${info.timestamp} [${info.level}] : ${info.message}`;
                })
            ),
            transports: [
              new winston.transports.File(options.file),
              new winston.transports.Console(options.console)
            ],
            exitOnError: false, // do not exit on handled exceptions
          });
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-03-30
            • 1970-01-01
            • 2016-03-08
            • 1970-01-01
            • 2017-04-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多