Logging HTTP Requests and Errors using Morgan.js

Morgan is a middleware for Node.js that simplifies HTTP request logging in Express applications. It automatically captures and formats request information, eliminating the need to write custom logging code manually.

Morgan helps gather logs from your server and prepares them for analysis. It provides many predefined formats and customization options, making it suitable for both small and large projects.

Installing Morgan

Install Morgan using npm:

npm install morgan

Then import it into your application:

const morgan = require('morgan')

Basic Usage Example

Here's a simple Express application using Morgan for logging:

const express = require('express')
const morgan = require('morgan')

const app = express()
const port = process.env.PORT || 8989

app.use(morgan('combined'))

app.get('/', function(req, res) {
   res.send('TutorialsPoint is Awesome!!!')
})

app.listen(port, () => {
   console.log(`Sample app listening at http://localhost:${port}`)
})

When you run this code, the console shows:

Sample app listening at http://localhost:8989

When you visit the URL, the browser displays:

TutorialsPoint is Awesome!!!

Morgan logs each request to the console:

::1 - - [28/Sep/2022:05:20:44 +0000] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0
(Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/104.0.0.0 Safari/537.36"

Predefined Log Formats

Morgan provides five predefined formats for quick setup:

  • combined ? Apache standard combined format with detailed information

  • common ? Apache standard common format

  • dev ? Color-coded format that changes color based on response status

  • short ? Shorter format with fewer details

  • tiny ? Minimal format with basic information

Example using the 'tiny' format:

app.use(morgan('tiny'))

The 'tiny' format produces output like:

GET / 200 - - 45.730 ms

Custom Format Strings

You can create custom formats using predefined tokens:

app.use(morgan(':method :url :res[content-length] - :response-time ms'))

Creating Custom Tokens

Morgan allows you to create custom tokens for logging specific data. For example, to log a custom HTTP header:

morgan.token('type-of-user', function(req, res) {
   return req.headers['type-of-user']
})

app.use(morgan(':method :url :status :type-of-user'))

This logs custom header information:

GET / 200 user

Saving Logs to Files

To redirect logs to a file instead of the console, create a write stream:

const fs = require('fs')
const path = require('path')

let logStream = fs.createWriteStream(path.join(__dirname, 'output.log'), {
   flags: 'a'
})

app.use(morgan('combined', {
   stream: logStream
}))

Advanced Custom Stream Example

You can create custom stream classes for more control over log output:

const { Writable } = require('stream')

class MyStream extends Writable {
   write(line) {
      console.log("Logger - ", line.toString())
   }
}

// Create a custom token
morgan.token("custom", "A new :method request for :url took :response-time ms")

let writer = new MyStream()

app.use(morgan('custom', {
   stream: writer
}))

Comparison of Formats

Format Information Level Best For
tiny Minimal Development
short Basic Light production logging
common Standard Basic production needs
combined Detailed Full production logging
dev Color-coded Development debugging

Conclusion

Morgan simplifies HTTP request logging with predefined formats and custom token support. Use it to monitor your Express applications efficiently, whether logging to console or files for production analysis.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements