Skip to main content

Steps to use Morgan in a Node.js Express application

organ is an HTTP request logger middleware for Node.js, primarily used with Express applications. It provides a way to log details about incoming requests and outgoing responses to the console or a file.
Steps to use Morgan in a Node.js Express application:
  • Initialize a Node.js project and install necessary packages:
Code
    mkdir my-express-app
    cd my-express-app
    npm init -y
    npm install express morgan --save
  • Create your main application file (e.g., index.js):
JavaScript
    // index.js
    const express = require('express');
    const morgan = require('morgan'); // Import morgan
    const app = express();
    const PORT = 3000;

    // Use morgan as middleware
    // You can choose a predefined format like 'dev', 'tiny', 'combined', 'common', 'short'
    app.use(morgan('dev'));

    // Define a simple route
    app.get('/', (req, res) => {
        res.send('Hello from Express!');
    });

    // Start the server
    app.listen(PORT, () => {
        console.log(`Server running on port ${PORT}`);
    });
Run your application.
Code
    node index.js
Now, when you send requests to your Express server (e.g., by visiting http://localhost:3000 in your browser), Morgan will log the request details to your console in the specified format (dev in this example).
Customizing Morgan's Output:
  • Predefined Formats: 
    Morgan offers various predefined formats like devtinycombinedcommon, and short, each providing different levels of detail in the logs.
  • Custom Format Strings: 
    You can create your own custom format strings using tokens like :method:url:status:response-time:req[header-name]:res[header-name], etc.
JavaScript
    app.use(morgan(':method :url :status :response-time ms - :res[content-length]'));
  • Custom Tokens: You can define your own custom tokens using morgan.token():
JavaScript
    morgan.token('host', function(req, res) {
        return req.hostname;
    });
    app.use(morgan(':method :host :status'));
  • Logging to a File: You can configure Morgan to write logs to a file instead of the console by providing a stream option:
JavaScript
    const fs = require('fs');
    const path = require('path');

    const accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' });

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