Contextual logger for Winston
Switch branches/tags
Clone or download
omichelsen Merge pull request #4 from gswalden/master
add syntax highlighting, fix typos
Latest commit 37ba260 Apr 20, 2017


Contextual logger for Winston, used for adding per-request context to server logs:

var WinstonContext = require('winston-context');
var logger = require('winston');

// Create a per-request child
var requestCtx = new WinstonContext(logger, '', {
    requestId: (Math.random()* 1e20).toString(36)
});'server.init'); // info: server.init requestId=2yn869172v40g

// User is authenticated, so we add userId
requestCtx = requestCtx.getContext('', { userId: 42 });'auth.ok'); // info: auth.ok requestId=2yn869172v40g userId=42

// We now have to log a lot of stuff for this user in a specific place
var log = requestCtx.getContext('server.system.subsystem');

log.warn('err', { what: 'User not found' }); // warn: sever.system.subsystem.err requestId=2yn869172v40g userId=24 what="User not found"


ctx = new WinstonContext(logger, [prefix, [meta]]) Creates a new contextual logger. It mocks .log and the per-level helpers set on the original logger.

ctx.log(level, name, meta, [meta, [...,]] callback) and ctx.{silly,debug,verbose,info,warn,error}(name, meta, callback) (or any other level-names you've given Winston) behave like they used to, except the added contextual prefix, meta-data and allows handling multiple meta-objects.

ctx.getContext([prefix, [meta]]) gets a contextual logger with the added prefix/meta-data. May be called recursively. Also of note is that it computes the complete prefix and meta-data at instantiation and gets a direct pointer to the parent logger (thus making long inheritance-chains performant).

WinstonContext.patchWinstonWithGetContext(winstonInstance) Monkey-patches the given instance of Winston with a .getContext() method that hands out new contexts as above.


Plenty! Please report them.