0
0
NodejsHow-ToBeginner · 4 min read

How to Use Morgan for Logging in Node.js

Use morgan as middleware in your Node.js Express app by importing it and calling app.use(morgan('combined')) to log HTTP requests. Morgan formats logs automatically and helps track requests easily during development or production.
📐

Syntax

The basic syntax to use Morgan in a Node.js Express app is:

  • const morgan = require('morgan'): Import Morgan library.
  • app.use(morgan('format')): Add Morgan as middleware with a chosen log format.

Common formats include 'combined', 'common', 'dev', 'short', and 'tiny'. Each format controls the detail level of logs.

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

const app = express();

// Use Morgan middleware with 'combined' format
app.use(morgan('combined'));
💻

Example

This example shows a simple Express server using Morgan to log HTTP requests in the 'dev' format. It logs method, URL, status, response time, and more.

javascript
import express from 'express';
import morgan from 'morgan';

const app = express();

// Use Morgan middleware with 'dev' format for concise colored logs
app.use(morgan('dev'));

app.get('/', (req, res) => {
  res.send('Hello, Morgan logging!');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 GET / 200 12.345 ms - 21
⚠️

Common Pitfalls

Common mistakes when using Morgan include:

  • Not installing Morgan with npm install morgan.
  • Forgetting to add Morgan as middleware with app.use().
  • Using Morgan after routes, so requests are not logged.
  • Using deprecated formats or custom tokens incorrectly.

Always add Morgan before your routes to ensure all requests are logged.

javascript
import express from 'express';
import morgan from 'morgan';

const app = express();

// WRONG: Morgan added after routes - no logs for these routes
app.get('/', (req, res) => {
  res.send('No logs here');
});

app.use(morgan('dev'));

// RIGHT: Morgan added before routes
// app.use(morgan('dev'));
// app.get('/', (req, res) => {
//   res.send('Logs will show here');
// });
📊

Quick Reference

Here is a quick reference for Morgan log formats:

FormatDescription
combinedStandard Apache combined log output
commonStandard Apache common log output
devConcise output colored by response status
shortShorter than default, including response time
tinyMinimal output: method, URL, status, response time

Key Takeaways

Install Morgan and add it as middleware before your routes with app.use(morgan('format')).
Choose a log format like 'dev' or 'combined' depending on your detail needs.
Morgan automatically logs HTTP request details to the console.
Always add Morgan before defining routes to ensure all requests are logged.
Avoid deprecated formats and ensure Morgan is installed correctly.