In my node application I use the Winstonjs logger. Today my application somehow seemed to freeze, but it failed to log something. I stopped the application and ran it manually which showed me this error
ReferenceError: totalValue is not defined
I clearly made a mistake in my code, but my main problem here is that I couldn't know from the Winston logs.
I pasted my Winston implementation below. I created this so that I can simply use log('The log message');
. But this doesn't log any occurring node errors.
Does anybody know how I can get every occurring node error into my Winston logs?
const myFormat = winston.format.printf(info => {
return `${info.timestamp} ${info.level}: ${info.message}`;
});
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(winston.format.timestamp(), myFormat), // winston.format.json(),
transports: [
new winston.transports.File({filename: 'logs/error.log', level: 'error'}),
new winston.transports.File({filename: 'logs/combined.log'}),
]
});
function log(message, level='info'){
if (typeof message === 'object'){
message = JSON.stringify(message);
}
logger[level](message);
}
Winston can log exceptions for you. From the docs: Exceptions
With winston, it is possible to catch and log uncaughtException events from your process. With your own logger instance you can enable this behavior when it's created or later on in your applications lifecycle:
const { createLogger, transports } = require('winston');
// Enable exception handling when you create your logger.
const logger = createLogger({
transports: [
new transports.File({ filename: 'combined.log' })
],
exceptionHandlers: [
new transports.File({ filename: 'exceptions.log' })
]
});
// Or enable it later on by adding a transport or using `.exceptions.handle`
const logger = createLogger({
transports: [
new transports.File({ filename: 'combined.log' })
]
});
// Call exceptions.handle with a transport to handle exceptions
logger.exceptions.handle(
new transports.File({ filename: 'exceptions.log' })