简体   繁体   English

如何为 winston@3 记录器制作自定义 json 格式化程序?

[英]How to make a custom json formatter for winston@3 logger?

I'm trying to make a custom json formatter for winston v3.我正在尝试为 winston v3 制作自定义 json 格式化程序。

Here is a single file with demo:这是带有演示的单个文件:

const { createLogger, format, transports } = require("winston")
const { combine, timestamp, prettyPrint } = format

const logger = createLogger({
  format: combine(timestamp(), prettyPrint())
})

logger.add(new transports.Console())

logger.info("test message", { data: { a: 1, b: [1, 2, 3, 4], d: new Date() } })

try {
  throw new Error("I'm an error!")
} catch (err) {
  logger.error(err)
}

It prints:它打印:

{ data: { a: 1, b: [ 1, 2, 3, 4 ], d: 2018-07-21T08:59:27.958Z },
  level: 'info',
  message: 'test message',
  timestamp: '2018-07-21T08:59:27.959Z',
  [Symbol(level)]: 'info',
  [Symbol(splat)]:
   [ { data: { a: 1, b: [ 1, 2, 3, 4 ], d: 2018-07-21T08:59:27.958Z } } ] }
{ Error: I'm an error!
    at Object.<anonymous> (/Users/max7z/projects/test/t32__test__winston__pretty-print_symbol/index.js:13:9)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:266:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:596:3)
  level: 'error',
  timestamp: '2018-07-21T08:59:27.962Z',
  [Symbol(level)]: 'error' }

I'd like to have almost the same output, but without some fields: [Symbol(level)], [Symbol(splat)].我想要几乎相同的输出,但没有一些字段:[Symbol(level)]、[Symbol(splat)]。

Is it possible to remove [Symbol] fields from prettyPrint formatter?是否可以从prettyPrint格式化程序中删除 [Symbol] 字段?

Or how can I make my own custom json formatter with error stacktrace like prettyPrint has?或者我怎样才能制作我自己的自定义 json 格式化程序,并带有像 PrettyPrint 这样的错误堆栈跟踪?

Check out how to create custom formats .查看 如何创建自定义格式 Then use the source code of prettyPrint as a base to create a modified version based on your needs.然后以prettyPrint源代码为基础,根据自己的需要创建修改后的版本。

Winstons uses triple-beam for definitions for the various Symbol s, so you can also use that package to remove them. Winstons 使用triple-beam来定义各种Symbol ,因此您也可以使用该包来删除它们。

I tested the sample with winston v3.3.3 and added a custom formatter to stringify the data object:我使用winston v3.3.3测试了示例,并添加了一个自定义格式化程序来对data对象进行字符串化:

const winston = require('winston');

const myFormatter = winston.format((info) => {
  const {message} = info;

  if (info.data) {
    info.message = `${message} ${JSON.stringify(info.data)}`;
    delete info.data; // We added `data` to the message so we can delete it
  }
  
  return info;
})();

const logger = winston.createLogger({
  format: winston.format.combine(
    winston.format.timestamp({
      format: 'YYYY-MM-DD HH:mm:ss',
    }),
    myFormatter,
    winston.format.simple(),
  ),
  transports: [
    new winston.transports.Console(),
  ],
});

I ran the commands from the question and got the desired output.我运行了问题中的命令并获得了所需的输出。

Execution:执行:

logger.info('test message', {data: {a: 1, b: [1, 2, 3, 4], d: new Date()}});

try {
  throw new Error(`I'm an error!`);
} catch (err) {
  logger.error(err);
}

Output:输出:

info: test message {"a":1,"b":[1,2,3,4],"d":"2020-09-09T09:41:22.525Z"} {"timestamp":"2020-09-09 11:41:22"}信息:测试消息 {"a":1,"b":[1,2,3,4],"d":"2020-09-09T09:41:22.525Z"} {"timestamp":"2020- 09-09 11:41:22"}

error: I'm an error!错误:我错了! {"timestamp":"2020-09-09 11:41:22"} {“时间戳”:“2020-09-09 11:41:22”}

The JSON object can be also printed with tabs and line breaks when using winston.format.prettyPrint() instead of winston.format.simple() .当使用winston.format.prettyPrint()而不是winston.format.simple()时,JSON 对象也可以用制表符和换行符打印。

Refer Winston format参考温斯顿格式

require('winston-daily-rotate-file');
const { createLogger, format, transports } = require('winston');
const { combine, timestamp, label, printf, prettyPrint, splat, simple } = format;


const myFormat = printf(info => {
    // you can get splat attribue here as info[Symbol.for("splat")]
    // if you custome splat please rem splat() into createLogger()
    return `${info.timestamp} [${info.label}] ${info.level}: ${info.message}`;
});

const logger = createLogger({
  format: combine(
    label({ label: 'keaz.co' }),
    timestamp(),
    splat(),
    myFormat
  ),
  transports: [
      new transports.Console(),
      new transports.File({
        filename: "info.log",
        level: 'info'
      }),
      new transports.File({
        filename: "error.log",
        level: 'error'
      })
    ]
})

logger.info("test message %o", { data: { a: 1, b: [1, 2, 3, 4], d: new Date() } });

module.exports = logger;

I've encountered kind of same problem and found solution in here .我遇到了类似的问题,并在此处找到了解决方案。 I am using Node.js and Socket.IO,I've used logger in Socket.IO.我正在使用 Node.js 和 Socket.IO,我在 Socket.IO 中使用了记录器。 As an example:举个例子:

Node.js节点.js

io.on('connection',function(socket){
  var date = new Date();
  socket.on('',function(data){
    logger.log('info', {IP: ip, Date: date, Path: '', Data: data.req_data});

Winston.js (logger) Winston.js (记录器)

const app_root = require('app-root-path');
const { createLogger, format, transports } = require('winston');


var logger = createLogger({
  level: 'info',
  format: format.combine(
    format(function(info, opts){
        console.log(`[${info.IP}]-[${info.Date}]-[${info.Path}]-[${info.Data}]`);
        return info;
    })(),
    format.json()

  ),

  transports: [
    new transports.File({filename: `${app_root}/logs/info.log`})
  ]
});

module.exports = logger;

As much as I understand we can use random variables(ip,date,bird,ball, etc..) as we want.据我所知,我们可以根据需要使用随机变量(ip、date、bird、ball 等)。 I think after little bit arrangment you can use this for errors too.我认为经过一点安排,您也可以将其用于错误。 Good luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM