How to set log level in Winston/Node.js

后端 未结 1 637
[愿得一人]
[愿得一人] 2021-02-12 02:56

I am using Winston logging with my Node.js app and have defined a file transport. Throughout my code, I log using either logger.error, logger.warn, or

相关标签:
1条回答
  • 2021-02-12 03:23

    If you are using the default logger, you can adjust the log levels like this:

    const winston = require('winston');
    // ...
    winston.level = 'debug';
    

    will set the log level to 'debug'. (Tested with winston 0.7.3, default logger is still around in 3.2.1).

    However, the documentation recommends creating a new logger with the appropriate log levels and then using that logger:

    const myLogger = winston.createLogger({
      level: 'debug'
    });
    myLogger.debug('hello world');
    

    If you are already using the default logger in your code base this may require you to replace all usages with this new logger that you are using:

    const winston = require('winston');
    // default logger
    winston.log('debug', 'default logger being used');
    
    // custom logger
    myLogger.log('debug', 'custom logger being used');
    
    0 讨论(0)
  • 2021-02-12 03:29

    Looks like there is a level option in the options passed covered here

    From that doc:

    var logger = new (winston.Logger)({
      transports: [
        new (winston.transports.Console)({ level: 'error' }),
        new (winston.transports.File)({ filename: 'somefile.log' })
      ]
    });
    

    Now, those examples show passing level in the option object to the console transport. When you use a file transport, I believe you would pass an options object that not only contains the filepath but also the level.

    That should lead to something like:

    var logger = new (winston.Logger)({
      transports: [
        new (winston.transports.File)({ filename: 'somefile.log', level: 'error' })
      ]
    });
    

    Per that doc, note also that as of 2.0, it exposes a setLevel method to change at runtime. Look in the Using Log Levels section of that doc.

    0 讨论(0)
提交回复
热议问题