Guide to Logging in Node.js
Posted By : Vignesh R | 22-Jul-2019
Logging is one of the important pieces of the software life cycle which can be taken for granted. With the good logging methodology followed can be helpful in debugging, without which it can consume hours and hours, even days of effort just to point out the cause.
Node.js generates text logs like any other application. For small scale application, the logs generated by Node itself can be enough, But for large scale application, it may not be of any use. Since these kinds of applications generate a massive amount of logs which could be reckless to track down. In this, we will go through some steps to generate a logging system for those kinds of applications.
1. Node.js V6.0 or above (To install Node.js in your machine follow steps on https://nodejs.org/en/).
2. Express.js (To install express in your project follow steps on https://expressjs.org/en/).
Express.js is a very simple framework that makes our life easy. The way of achieving this has been eliminating the maximum number of operations, having only necessary for its operation.
The ability to identify the request to which a log belongs is a very important feature. So Express needs to solve this problem.
Passing request object throughout the code could not be a suitable solution for two main reasons,
1. Passing an extra parameter would make the code dirty.
2. The API module would be joined to the rest of the modules, which is an excessively tedious task.
This is a library that will do all the work for Us. As it uses Winston behind the hood, Even the earlier configuration could work for the same, or the new configuration can be passed to it. In each line of the log, you will add the req id in a unique way when a request arrives in the Express.
Setting up is very simple. Add the express-logger-unique-req-id in your project.
npm install express-logger-unique-req-id --save
Below is the simple example of the logger object.
var express= require('express’); var app = express(); var express_logger = require(‘./express-logger-unique-req-id’); express_logger.initializeLogger(app); let logger = express_logger.getLogger(); logger.debug(‘First message’);
With this simple example, we already have a logger object that we can use to print the unique req id at any point of time over a request.