3

我刚刚实现了 Winston Logging,它按预期工作,但我遇到了一些我无法找到答案的问题。

据我所知,winston 的工作方式,设置的日志级别和低于优先级的任何内容,比如在错误时它还将包括信息日志等。有没有办法创建一个特定的日志级别让我们称之为 HTTP或 db 我只记录 http 或 db 事件,它们不会出现在组合文件或控制台中?

4

2 回答 2

5

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).

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'
});
于 2019-07-06T23:43:28.157 回答
0

我可以用参数初始化一个winston,在你的情况下是文件名。我使用类似的设置来记录单独的 cron 任务(我使用type参数代替filename,它用作日志中的前缀,因此我可以在一个日志文件中识别多个 cron 任务中的问题)。我希望你熟悉 ES6 语法。

实用程序/winston.js

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

const infoLogger = filename => createLogger({
    transports: [
        new transports.File({
            filename: 'info-' + filename,
            level: 'info'
        }),
        new transports.Console(),
    ],
        exitOnError: false
    });

const errorLogger = filename => createLogger({
    transports: [
        new transports.File({
            filename: 'error-' + filename,
            level: 'error'
        }),
        new transports.Console(),
    ],
        exitOnError: false
    });

export default filename => ({
    errorLogger: errorLogger(filename).error,
    infoLogger: infoLogger(filename).info
});

因此,在您的代码中,您可以从 utils 导入自定义 winston 设置并使用文件名对其进行初始化。请注意,我基本上只从 winston 导出错误函数errorLogger(filename).error,您可以按照您可以接受的方式对其进行修改

main.js

import logger from './utils/winston';
const { errorLogger, infoLogger } = logger('http.log');
errorLogger('some http fail'); // destination file => error-http.log
infoLogger('some http info'); // destination file => info-http.log
于 2019-07-05T19:57:27.137 回答