Error Logging in Node
From Logic Wiki
Contents
Installation
npm i winston
Setup
const winston = require('winston');
...
winston.add(winston.transports.File, {filename:'logfile.log'})
Usage
winston.log('error', err.message);
or
winston.error(err.message, error); // error // warn // info // verbose // debug // silly
Logging to MongoDb
npm i winston-mongodb@3.0.0
require('winston-mongodb');
winston.add(winston.transports.MongoDB, { db: 'mongodb://localhost/somedb' });
To set only the errors to go to db
winston.add(winston.transports.MongoDB, { db: 'mongodb://localhost/somedb', level:'error' });
if we give the parameter as info error, warn and info will be logged.
Uncaught Exception
in index.js
process.on('uncaughtException', (ex) => {
winston.error(ex.message, ex);
});
Unhandled Promise Rejections
process.on('uncaughtRejection', (ex) => {
winston.error(ex.message, ex);
});
Handling Exceptions
this line below is replacement of Uncaught Exceptions.
winston.handleExceptions(new winston.transports.File({filename:'uncaughtExceptions.log'}));