Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable winston logging when running unit tests?

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
  }
}   
like image 933
Sk606 Avatar asked Jul 13 '16 23:07

Sk606


People also ask

How can I disable logging while running unit tests in Java?

You can disable LogLog's output by calling LogLog. setQuietMode(true) .

Should you log in unit tests?

I would definitely consider unit tests for logging scenarios. when testing, think about the information you would require in a situation where the code has failed. if you have a live issue you'd want to be reassured that you have enough information to find the cause of the issue.

Is Winston logging async?

The Nodejitsu team has released Winston, a pluggable, async logger for Node. js that also supports multiple transports.


3 Answers

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
like image 156
Mark Avatar answered Oct 20 '22 23:10

Mark


What I do is a bit ugly, but allows me to keep using Jest's --silent option normally. I just set Winston's silent to process.argv.indexOf("--silent") >= 0. For example:

const logger = new winston.Logger({
  …,
  transports: [
    new winston.transports.Console({
      …,
      silent: process.argv.indexOf("--silent") >= 0,
    }),
  ],
});
like image 36
Rubén Illodo Brea Avatar answered Oct 20 '22 22:10

Rubén Illodo Brea


Create a logger:

const logger = createLogger({
    level: "info",
    format: format.json(),
    transports: []
});

Silence all logging:

logger.transports.forEach((t) => (t.silent = true));
like image 17
shusson Avatar answered Oct 20 '22 21:10

shusson