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
}
}
You can disable LogLog's output by calling LogLog. setQuietMode(true) .
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.
The Nodejitsu team has released Winston, a pluggable, async logger for Node. js that also supports multiple transports.
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
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,
}),
],
});
Create a logger:
const logger = createLogger({
level: "info",
format: format.json(),
transports: []
});
Silence all logging:
logger.transports.forEach((t) => (t.silent = true));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With