Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
var logger = require('winston');
// override winston.logger.log to add stacktrace along errors included
// 4 ways to include some errors in a log:
// - logger.warn('message', myError)
// - logger.warn('message', [myError1, myError2])
// - logger.warn('message', { error: myError })
// - logger.warn('message', { errors: [myError1, myError2] })
(function(logger) {
var _log = logger.log;
logger.log = function() {
var self = this,
errs = [],
args = Array.prototype.slice.call(arguments),
callback = typeof args[args.length - 1] === 'function' ? args.pop() : null,
meta = typeof args[args.length - 1] === 'object' ? args.pop() : {},
isError = function(a) { return a instanceof Error };
// logger.warn('message', myError)
if (meta instanceof Error) {
errs = [meta];
meta = {};
// logger.warn('message', { error: myError })
} else if (meta.error instanceof Error) {
errs = [meta.error];
delete meta.error;
// logger.warn('message', { errors: [myError1, myError2] })
} else if (meta.errors && _(meta.errors).every(isError)) {
errs = meta.errors;
delete meta.errors;
// logger.warn('message', [myError1, myError2])
} else if (_(meta).isArray() && _(meta).every(isError)) {
errs = meta;
meta = {};
}
// finally attach the processed result
if (errs && errs.length) {
meta.errors = _(errs).map(function(err) {
return _(err).pick('name', 'message', 'stack');
});
// if no message on the log, compute one from the first error message
// supports: logger.warn(myError) or logger.warn([myError, myError2, etc...]) or ...
if (args.length < 2) {
args.push(meta.errors[0].message);
}
}
args.push(meta);
if (callback) args.push(callback);
_log.apply(logger, args);
};
})(logger);
// tests
logger.warn('test');
logger.warn('test2', {a: 1});
logger.warn('test3', new Error('test3'));
logger.warn('test4', [ new Error('test4-1'), new Error('test4-2') ]);
logger.warn('test5', { error: new Error('test5') });
logger.warn('test6', { errors: [ new Error('test6-1'), new Error('test6-2') ] });
logger.warn(new Error('test3'));
logger.warn([ new Error('test7-1'), new Error('test7-2') ]);
logger.warn({ error: new Error('test8') });
logger.warn({ errors: [ new Error('test9-1'), new Error('test9-2') ] });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.