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.
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.
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.
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.
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*/ ] });
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With