I was looking at top Node logging systems: npmlog
, log4js
, bunyan
and winston
and decided to use winston
for having the most npm
monthly downloads.
What I want to set up is custom logger which I will be able to use on development environment with logger.debug(...)
which won't log anything on production environment. This will help me so when I'm on development environment, I won't need to write anything since I'll see all the outputs.
This is what I have now:
var level = 'debug';
if (process.env.NODE_ENV !== 'development'){
level = 'production'; // this will never be logged!
}
var logger = new winston.Logger({
transports: [
// some other loggings
new winston.transports.Console({
name: 'debug-console',
level: level,
prettyPrint: true,
handleExceptions: true,
json: false,
colorize: true
})
],
exitOnError: false // don't crush no error
});
Problem occurs when I'm trying to log JavaScript Object
or Javascript Array
. With Object
, I need to do toJSON()
, and for Array
I need first JSON.stringify()
and then JSON.parse()
.
It's not nice to write all the time this methods, just to log something that I want. Furthermore, it's not even resource-friendly, because those formatting methods need to be executed before logger.debug()
realises that it's on production and that it shouldn't log it in the first place (basically, it's evaluating arguments before function call). I just like how old-fashined console.log()
logs JavaScript objects and arrays.
Now, as I'm writing this question, I found that there is a way of describing custom format for every winston transports
object. Is that the way of doing it, or is there some other way?
logger.log("info", "Starting up with config %j", config);
Winstons uses the built-in utils.format library. https://nodejs.org/dist/latest/docs/api/util.html#util_util_format_format_args