Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs winston - Logging with multiple arguments

I was trying to use winston for logging, but I am seeing that if I want to get the data with 2 arg, then I am getting the log, but if I want to get 3 arguments, then I am not getting the data,

Ex:

logger = new (winston.Logger)({
transports: [
   new (winston.transports.Console)({colorize : true, timestamp:true}),
 ]
});

Now trying to get the log as below:

 1. logger.info("We got the data %s, %d", data, port);
 O/P: We got the data %s, %d  => No data and port value
 2. logger.info("We got the data, port", data, port);
 O/P: We got the data, port   => No data and port value
 3. logger.info("We got the data", data);
 ===> Getting the data correctly.

Can you please let me know what I was missing in 1, 2 or does winston not log the data in case 1 & 2 really?

like image 834
user1887432 Avatar asked Feb 12 '13 16:02

user1887432


1 Answers

This is what worked for me and winston 3.2.x:

const { format, createLogger, transports } = require('winston');
const jsonStringify = require('fast-safe-stringify');

const logLikeFormat = {
  transform(info) {
    const { timestamp, label, message } = info;
    const level = info[Symbol.for('level')];
    const args = info[Symbol.for('splat')];
    const strArgs = args.map(jsonStringify).join(' ');
    info[Symbol.for('message')] = `${timestamp} [${label}] ${level}: ${message} ${strArgs}`;
    return info;
  }
};

const debugFormat = {
  transform(info) {
    console.log(info);
    return info;
  }
};

const logger = createLogger({
  format: format.combine(
    // debugFormat, // uncomment to see the internal log structure
    format.timestamp(),
    format.label({ label: 'myLabel' }),
    logLikeFormat,
    // debugFormat, // uncomment to see the internal log structure
  ),
  transports: [
    new transports.Console()
  ]
});


logger.info('foo', 'bar', 1, [2, 3], true, { name: 'John' });

which results in: 2019-07-04T21:30:08.455Z [myLabel] info: foo "bar" 1 [2,3] true {"name":"John"}

Basically format.combine sets a pipeline for an info object. For each format function, transform is called and the final log message should be written to info[Symbol.for('message')] hope this helps

like image 143
pgorecki Avatar answered Dec 06 '22 11:12

pgorecki