Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging with Winston in Express.js - how to configure for different environments?

I've started to use Winston for logging errors and events with my node/express.js app.

One thing I have not figured out is how to specify different Winston transports (or other config) for different environments (Dev/Test/Production). E.g. I want to have everything logged to the console in the dev enviroment, but use a different transport in Production.

Anyone know how to do this?

like image 456
UpTheCreek Avatar asked Oct 31 '12 11:10

UpTheCreek


1 Answers

To my knowledge, there's no "standard" way to do this, but you might do something like this:

var myLogTransports = [];

if (process.env.NODE_ENV == 'production') {
  myLogTransports.push(new (winston.transports.File)({ filename: 'somefile.log' }));
}
else {
  myLogTransports.push(new (winston.transports.Console)({ level: 'error' })));
}

var logger = new (winston.Logger)({
  transports: myLogTransports,
});

Winston now supports adding loggers dynamically. See the Working with Transports section for more information. The original answer could be rewritten like this:

var logger = new winston.Logger();

if (process.env.NODE_ENV == 'production') {
  logger.add(winston.transports.File, { filename: 'somefile.log' });
}
else {
  logger.add(winston.transports.Console, { level: 'error' });
}
like image 109
mikl Avatar answered Oct 28 '22 11:10

mikl