Morgan Logger Middleware Dor NodeJs

Posted By : Nisheet Sharma | 26-Jun-2018

Morgan is a logger middleware for Node, that can be easily customized to suit your application's needs. You can set it automatically log all requests on your server. We can even create a log file and stream all the logs into it rather than displaying it on the console, which would be helpful in a production environment.

 

Installation:

1. Here's the command to install it via npm:
npm i morgan

 

Usage:

First, lets fetch the middleware into our application using require as follows:

var morgan = require('morgan')

 

The basic syntax for usage is morgan(format,options), where:


1. format - It can be a string or a function. We can pass, any one of the pre-defined formats, or create a string with some pre-defined tokens provided by morgan to construct custom patterns. Additionally, we can even pass a function, that takes tokens, req, res as arguments, and utilizes the tokens' sub methods to construct a custom pattern for logging.

morgan(':method :url :status :res[content-length] - :response-time ms');

 


Here are some of the pre-defined strings and their internally used tokens, that you can use to format the logs:

i. combined - Useful for production environments. Shows the time, method, url to which the request is made, status code, response, and also the client's user agent/browser.

:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"

 

ii. common - Its similar to combined, only difference is it does not show the user agent of the client.

:remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]

iii. dev - This is meant to be used for development only. Its colors the status code differently for each of the standard HTTP response codes.

:method :url :status :response-time ms - :res[content-length]

 

Here's an example of creating format patterns via a function.

 

morgan(function (tokens, req, res) {
  return [
    tokens.method(req, res),
    tokens.url(req, res),
    tokens.status(req, res),
    tokens.res(req, res, 'content-length'), '-',
    tokens['response-time'](req, res), 'ms'
  ].join(' ')
});
 
2. options - This is the options object, we will use to tweak the behaviour of the morgan logger. It can take the following properties:

i. immediate - By default, morgan only displays the logs, once the server responds to a request. So, in case, your server crashes before sending a response, morgan will not display that request at all. If you wish to see the request logged irrespective of the server response, set it to true.
ii. skip - This property can be used to skip log outputs based on some custom logic, like for example, if we wish to log only error responses we can do the following:

 

// EXAMPLE: only log error responses
morgan('combined', {
  skip: function (req, res) { return res.statusCode < 400 }
});

 

iii. stream - We can pass an Output stream here, to log the outputs into a file for example.

 

   var express = require('express');
   var fs = require('fs');
   var morgan = require('morgan');
   var path = require('path');
   var app = express();   

// create a write stream (in append mode) 
var accessLogStream = fs.createWriteStream(path.join(__dirname,'access.log'),{flags : 'a '});

// setup the logger 
app.use(morgan('combined', {stream : accessLogStream }));
app.get('/', function(req , res) {   
   res.send('hello, world!');     
});

About Author

Author Image
Nisheet Sharma

Nisheet is a Full Stack Developer (MEAN). He is familiar with C, C++, Java, Html, Css, JavaScript, MySql, MongoDb, AngularJs, NodeJs, ExpressJs.

Request for Proposal

Name is required

Comment is required

Sending message..