Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: Winston: Can I add default meta data to all log messages

I'm using Winston in Node.js for logging. I know I can add metadata individually to each log message but is there a way to specify a default set of metadata that'll be added to every log message (such as the app name) as I don't want to specify it every time I need to send a log message.

like image 633
Sean Bannister Avatar asked Feb 21 '12 16:02

Sean Bannister


People also ask

What is meta data in Nodejs?

Metadata is useful for storing additional, structured information on an object. As an example, you could store your user's full name and corresponding unique identifier from your system on a Stripe Customer object.

How do you log objects in Winston?

Winston should log your object with this set up. Show activity on this post. Show activity on this post. const winston = require("winston"); const { format, transports, createLogger } = winston; const path = require("path"); const consoleloggerLevel = process.

What is Winston logger in node JS?

Winston is the most popular logging library for Node. js. It aims to make logging more flexible and extensible by decoupling different aspects such as log levels, formatting, and storage so that each API is independent and many combinations are supported. It also uses Node.


2 Answers

For Winston v2 (see comments)

There are now rewriters.

For example, the below will add a property app to every metadata going through this logger.

    logger.rewriters.push(function(level, msg, meta) {       meta.app = 'myApp';       return meta;     }); 

You can also declare it when building the logger:

    new (winston.Logger)({             level: config.log[file].level,             rewriters: [                 (level, msg, meta) => {                     meta.app = 'myApp';                     return meta;                 }             ],             transports: [                 /*your transports*/             ]     }); 
like image 180
DrakaSAN Avatar answered Sep 23 '22 16:09

DrakaSAN


For Winston v3:

const addAppNameFormat = winston.format(info => {   info.appName = "My Program";   return info; });  const logger = winston.createLogger({   format: winston.format.combine(     addAppNameFormat(),     winston.format.json()   ), transports: [new winston.transports.Console()] });  logger.warn('Danger Will Robinson!'); // {"message":"Danger Will Robinson!","level":"warn","appName":"My Program"} 

See: https://github.com/winstonjs/winston/blob/HEAD/UPGRADE-3.0.md#migrating-filters-and-rewriters-to-formats-in-winston3

like image 33
shadowspawn Avatar answered Sep 21 '22 16:09

shadowspawn