Winston/Morgan日志记录,避免重复输入 [英] Winston / Morgan logging avoiding duplicate entries

查看:77
本文介绍了Winston/Morgan日志记录,避免重复输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚实现了Winston Logging,它可以按预期工作,但是遇到了一些我找不到答案的问题.

I just implemented Winston Logging and it works as expected but i came accross a few issues which i cant find answer for.

据我所知,winston的工作方式,设置的日志级别以及使用优先级以下的任何内容,例如出错时,它还将包括信息日志等.是否可以通过创建特定日志级别的方法来让称它为HTTP还是db,我仅将http或db事件记录到其中,而它们并没有出现在合并的文件或控制台中?

The way winston works as far as i can tell, the set log level and anything below as far as priority gets used, like on error it will also include info logs etc. Is there a way to create a specific log level lets call it HTTP or db where i only log http or db events to and they don't end up in the combined file or console ?

推荐答案

更好的解决方案是使用具有格式功能的单个记录器作为级别过滤器",以指定哪个传输日志记录哪个特定级别.这是解决方案(请注意,levelFilter可以轻松扩展为可接受级别的数组).

A better solution is to use a single logger with a format function as a "level filter" to specify which transport logs which specific level. Here is the solution (note, levelFilter could easily be extended to take an array of acceptable levels).

关键见解是,如果格式化程序链中未返回任何info对象,则不会记录任何内容.

The key insight is that if no info object is returned from the formatter chain, nothing gets logged.

const { createLogger, format, transports } = require('winston');

const levelFilter = (level) =>
  format((info, opts) => {
     if (info.level != level) { return false; }
      return info;
  })();

const logger = createLogger({
  transports: [
    new transports.Console({
        format: format.combine(
          levelFilter("info"),
          format.json()
        )
    }),
    new transports.File({
        filename: "test.log",
        format: format.combine(
          levelFilter("error"),
          format.json()
        )
    }),
  ]
});

// ONLY is logged to test.log
logger.log({
  level: 'error',
  message: 'abcd'
});

// ONLY is logged to console
logger.log({
  level: 'info',
  message: '1234'
});

这篇关于Winston/Morgan日志记录,避免重复输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆