Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

node.js - Winston / Morgan logging avoiding duplicate entries

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

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...