I am using Winston for logging in my TypeScript application. I want to log errors with stack traces, even when the error is a string. Below is my current Winston setup and a sample controller function where I am throwing a string error.
Winston Setup:-
import { createLogger, format, transports } from "winston";
const { combine, timestamp, printf, colorize, errors } = format;
const logFormat = printf(({ level, message, timestamp, stack }) => {
if (stack) {
return `${timestamp} ${level}: ${message} - ${stack}`;
}
return `${timestamp} ${level}: ${message}`;
});
const logger = createLogger({
format: combine(errors({ stack: true }), colorize(), timestamp(), logFormat),
transports: [new transports.Console()],
});
export { logger };
**Controller Function :- **
async function addNewBreed(req: Request, res: Response) {
try {
const existing_breed = await BreedService.findBreed({
where: {
name: req.body.name,
},
});
if (existing_breed) {
throw localeKeys.BREED_ALREADY_EXISTS;
}
const created_breed = await BreedService.addNewBreed(req.body);
return actionCompleteResponse({ res, data: created_breed });
} catch (error) {
logger.error("addNewBreed", error);
return sendError({ res, error });
}
}
localKeys.ts :-
{
BREED_ALREADY_EXISTS: “Breed already exists.”,
}
Problem :-
When I throw an error using a string from my localization file (localeKeys.BREED_ALREADY_EXISTS), Winston logs the error message but does not include the stack trace. How can I ensure that Winston logs stack traces for string errors as well ?
Attempts :-
I have tried using the errors({ stack: true }) format in Winston, but it doesn’t seem to work for string errors.
Jaskaran is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.