Winston : understanding logging levels

2020-06-30 13:14发布

Reading and fiddling with Winston, I'm puzzled as to why the logging levels are ordered as they are and why the transports behave in the way they do (well, at least the Console one). I'd appreciate if someone could, perhaps even thoroughly, with real use case examples, explain why logging with Winston works this way?

For example, I setup my logger like this :

var logger = new (winston.Logger)({
  levels: winston.config.syslog.levels,
  colors: winston.config.syslog.colors,
  level: "debug",  // I'm not sure what this option even does here???
  transports: [
    new (winston.transports.Console)({
      colorize: true,
      handleExceptions: true,
      json: false,
      level: "debug"
    })
  ]
});

So, if I do logger.debug("Test");, then it will log debug: Test, fine. But if I do logger.info("Test");, then nothing happens.

The problem I have is that, If I want to log to the console eveverything but debug messages, what do I do? ... or even debug and info messages, but log everything else?

Coming from a Java world, using the standard loggers, I am used to having debug being more "fine grained" than warn and the loggers worked backwards; setting the logging level to info, for example, did log everything but debug (or something).

Also, what if I'd like a logger to log only error, warning and info messages, how would I do that with Winston?

* EDIT *

Apparently, this order of level is unique to winston.config.syslog.levels. So the only question remaining is : "Is it possible to, somehow, restrict a transport to a very specific logging level only?"

2条回答
闹够了就滚
2楼-- · 2020-06-30 13:39
var logger = new (winston.Logger)({
       levels: {
        'info': 0,
        'ok': 1,
        'error': 2
       },
    colors: {
        'info': 'red',
        'ok': 'green',
        'error': 'yellow'
       },
    transports: [
        new (winston.transports.Console)({level:'info',colorize: true})
    ]
});
logger.log('info',"This is info level");
logger.info("This is info level");
查看更多
冷血范
3楼-- · 2020-06-30 13:46

As per the documentation, you can set your own Logging levels, 0 being lowest, and associate colours with it. Now, if you don't want to log the lowest level, just set the level property to the corresponding level. By default, the console logger has it's level set to info

So, here is an example:

logger = new (winston.Logger)({
  levels: {
    'info': 0,
    'ok': 1,
    'error': 2
  }
  transports: [
    new (winston.transports.ConsoleTransport)(silent: options.silent, level: 'ok')
  ]
});
查看更多
登录 后发表回答