Search code examples
javascriptnode.jswinston

Customize messages format using winston.js and node.js


I'm using winston.js in my nodejs project, what I'm looking for is, to output two different custom messages into different type of transport (console,file). console mode:

return `${timestamp} [${label}] ${level}: ${message}

file mode (in the file I want to display only the message and level) :

return ` ${level} : ${message}

Here's my code :

const { createLogger, format, transports } = require('winston');
const { combine, timestamp, label, printf } = format;
const myFormat = printf(({ level, message, label, timestamp }) => {

 return `${timestamp} [${label}] ${level}: ${message}`;
  }
 });

const logger = createLogger({
 format: combine(
  label({ label: 'hello  |' }),
  timestamp(),
  myFormat
),
transports: [new transports.Console(),
  new transports.File({
   filename: api.log,
   level: 'info'
  })
]
 });
 logger.stream = {
   write: function(message, encoding) {

   logger.info(message);
 },
  };
 module.exports = logger;

With this code I have the same output, any help please?


Solution

  • From Winston.js ver3 on Transport accepts Format

    In order to have different log format for different outputs you need to create different Format objects and pass them to your Transport constructors.

    So in your case:

    • You've created myFormat for ${timestamp} [${label}] ${level}: ${message} instead of passing it to createLogger you need to pass it to Console constructor.
    • You need to create another Format for ${level} : ${message}
    • Pass that Format to format property of File transport constructor

    You can see example with passing different format to Console in winston.js project source: https://github.com/winstonjs/winston/blob/master/examples/quick-start.js