How to Log Full Stack Trace with Winston 3?
My logger is set up like:
const myFormat = printf(info => {
return `${info.timestamp}: ${info.level}: ${info.message}: ${info.err}`;
});
const logger =
winston.createLogger({
level: "info",
format: combine(timestamp(), myFormat),
transports: [
new winston.transports.File({
filename:
"./logger/error.log",
level: "error"
}),
new winston.transports.File({
filename:
"./logger/info.log",
level: "info"
})
]
})
Then I am logging out some error like this:
logger.error(`GET on /history`, { err });
How is it possible to log the full stack trace for errors to via the error transport? I tried passing in the err.stack and it came out as undefined.
Thanks !
Solution 1:
For winston version 3.2.0+
, following will add stacktrace to log output:
import { createLogger, format, transports } from 'winston';
const { combine, timestamp, prettyPrint, colorize, errors, } = format;
const logger = createLogger({
format: combine(
errors({ stack: true }), // <-- use errors format
colorize(),
timestamp(),
prettyPrint()
),
transports: [new transports.Console()],
});
Ref: https://github.com/winstonjs/winston/issues/1338#issuecomment-482784056
Solution 2:
You can write a formatter to pass error.stack
to log.
const errorStackFormat = winston.format(info => {
if (info instanceof Error) {
return Object.assign({}, info, {
stack: info.stack,
message: info.message
})
}
return info
})
const logger = winston.createLogger({
transports: [ ... ],
format: winston.format.combine(errorStackFormat(), myFormat)
})
logger.info(new Error('yo')) // => {message: 'yo', stack: "Error blut at xxx.js:xx ......"}
(the output will depend on your configuration)
Solution 3:
UPDATE 1/14/2021 - This no longer works in newer versions of Winston.
Original Answer
@Ming's answer got me partly there, but to have a string description with the error, this is how I got full stack tracing working on ours:
import winston from "winston";
const errorStackTracerFormat = winston.format(info => {
if (info.meta && info.meta instanceof Error) {
info.message = `${info.message} ${info.meta.stack}`;
}
return info;
});
const logger = winston.createLogger({
format: winston.format.combine(
winston.format.splat(), // Necessary to produce the 'meta' property
errorStackTracerFormat(),
winston.format.simple()
)
});
logger.error("Does this work?", new Error("Yup!"));
// The log output:
// error: Does this work? Error: Yup!
// at Object.<anonymous> (/path/to/file.ts:18:33)
// at ...
// at ...