Disable winston logging when running unit tests?

Sk606 picture Sk606 · Jul 14, 2016 · Viewed 21.6k times · Source

Can Winston logging be selectively disabled when executing unit tests of a node module?

Ideally, I'd like to have logging for informational and debug purposes when the application is running, but be suppressed as to not clutter the presentation unit test results when I run my tests.

My use of winston is internal to my module, something like this:

// MyModule.js
var logger = require('winston');
module.exports = function() {
  // does some stuff
  // and logs some stuff like so:
  logger.log('an informational message');
}

// MyModuleTest.js
describe('MyModule', fucntion() {
  it('should do some stuff', function() {
     var myModuleUnderTest = require('MyModule');
     // some tests
  }
}   

Answer

Mark picture Mark · Aug 28, 2017

Winston transports have a silent property that you can set, which is probably a little nicer than removing the entire transport.

I add a name to the transports to make is a little easier like this:

var logger = new winston.Logger();

logger.add(winston.transports.Console, {
    name: 'console.info',
    colorize: true,
    showLevel: true,
    formatter: consoleFormatter,
})

Then in the test or set-up I can selectively turn logging on and off with:

logger.transports['console.info'].silent = true  // turns off
logger.transports['console.info'].silent = false // logging back on