Difference between revisions of "Error Logging in Node"

From Logic Wiki
Jump to: navigation, search
 
(One intermediate revision by the same user not shown)
Line 28: Line 28:
 
  winston.add(winston.transports.MongoDB, { db: 'mongodb://localhost/somedb', level:'error' });
 
  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.
 
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'}));

Latest revision as of 13:01, 8 November 2018


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'}));