Skip to content

Instantly share code, notes, and snippets.

@mostr
Last active January 18, 2017 15:05
Show Gist options
  • Save mostr/91b0841efaf510b56cea1f95db0c2f98 to your computer and use it in GitHub Desktop.
Save mostr/91b0841efaf510b56cea1f95db0c2f98 to your computer and use it in GitHub Desktop.
Winston wrapper
let winston = require('winston');
// instantiate winston logger
// configure rewriters to add TID and application name to "meta"
// ...
function wrapWinston(logger) {
return ['debug', 'warn', 'info', 'error'].reduce((res, e) => {
res[e] = function(msg, ...extras) {
return logger[e].call(logger, msg, mergeExtraArgs(extras));
};
return res;
}, {});
}
function mergeExtraArgs(objects) {
return objects.reduce((result, el, index) => {
result[index] = el instanceof Error ? {name: el.name, message: el.message, stack: el.stack} : el;
return result;
}, {});
}
// use it
let logger = wrapWinston(winston);
logger.info('This is info', {foo: {bar: 'baz'}}, {id: 42, name: 'foobar'});
logger.error('This is error', new Error('Boom'));
{
"0": {
"foo": {
"bar": "baz"
}
},
"1": {
"id": 42,
"name": "foobar"
},
"__TID": "123",
"application": "testapp",
"level": "info",
"message": "This is info",
"timestamp": "2017-01-18T14:55:00.049Z"
}
{
"0": {
"name": "Error",
"message": "Boom",
"stack": "Error: Boom\n at Object.<anonymous> (/Users/michal/Devel/Tmp/logtest/logtest.js:67:31)\n at Module._compile (module.js:570:32)\n at Object.Module._extensions..js (module.js:579:10)\n at Module.load (module.js:487:32)\n at tryModuleLoad (module.js:446:12)\n at Function.Module._load (module.js:438:3)\n at Module.runMain (module.js:604:10)\n at run (bootstrap_node.js:394:7)\n at startup (bootstrap_node.js:149:9)\n at bootstrap_node.js:509:3"
},
"__TID": "456",
"application": "testapp",
"level": "error",
"message": "This is error",
"timestamp": "2017-01-18T14:55:00.053Z"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment