Thanks for this solution. It's unbelievable that the winston developers still haven't fixed this issue after so many years. Anyway, since this problem only seems to happen with Error objects, it's better to only apply your toJSON() transformation for messages that are actually Error objects. Here's a little function that does that -- it wraps logger.log() and all the other methods, too.
import winston from 'winston';
import clone from 'utils-deep-clone';
function fixErrorHandling(logger) {
['log', 'error', 'warn', 'info', 'http', 'verbose', 'debug', 'silly'].forEach(
(method) => {
const [orig, pos] = [Symbol(), method === 'log' ? 1 : 0];
logger[orig] = logger[method];
logger[method] = (...args) => {
if (args[pos] instanceof Error) {
args[pos] = clone.toJSON(args[pos]);
}
return logger[orig](...args);
};
}
);
}
const log = winston.createLogger({
format: winston.format.simple(),
transports: [new winston.transports.Console()],
});
fixErrorHandling(log);
log.error(new Error('uh oh'));
Thanks for this solution. It's unbelievable that the winston developers still haven't fixed this issue after so many years. Anyway, since this problem only seems to happen with Error objects, it's better to only apply your
toJSON()transformation for messages that are actually Error objects. Here's a little function that does that -- it wrapslogger.log()and all the other methods, too.