Advanced use case of morgan middleware in express
Here's a more complex use case for morgan
in an Express.js application, where we customize the logging format and also log to a file using a rotating file stream for better management of logs:
-
Install Dependencies: You'll need
morgan
,rotating-file-stream
, andfs
(Node.js filesystem module) if not already installed:npm install morgan rotating-file-stream fs
-
Setting Up
morgan
with Rotating File Stream:const express = require('express'); const morgan = require('morgan'); const fs = require('fs'); const path = require('path'); const rfs = require('rotating-file-stream'); const app = express(); // Define log directory and create it if it doesn't exist const logDirectory = path.join(__dirname, 'log'); fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory); // Create a rotating write stream for log files const accessLogStream = rfs.createStream('access.log', { interval: '1d', // rotate daily path: logDirectory }); // Define custom token for logging request processing time morgan.token('response-time-ms', function(req, res) { return `${res['response-time']}ms`; }); // Use morgan middleware with custom format and stream app.use(morgan(':date[iso] :method :url :status :response-time-ms', { stream: accessLogStream })); // Example route app.get('/', (req, res) => { res.send('Hello World!'); }); // Start the server const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
-
Explanation:
const rfs = require('rotating-file-stream');
: This module provides a rotating file stream which automatically rotates log files based on size or date.const accessLogStream = rfs.createStream('access.log', { options });
: Creates a rotating file stream namedaccess.log
in thelog
directory. It rotates daily (interval: '1d'
) and stores logs in the specifiedlogDirectory
.morgan.token('response-time-ms', function(req, res) { ... });
: Defines a custom tokenresponse-time-ms
to log the response time in milliseconds (res['response-time']
).app.use(morgan(':date[iso] :method :url :status :response-time-ms', { stream: accessLogStream }));
: Usesmorgan
middleware with a custom logging format that includes the date in ISO format, HTTP method, URL, response status, and response time in milliseconds. It streams the log output toaccessLogStream
.
-
Running the Application:
- When you run your Express application with this setup,
morgan
will log each request's details (HTTP method, URL, status, response time) to both the console and theaccess.log
file in thelog
directory. The logs will be rotated daily as specified.
- When you run your Express application with this setup,
This setup is useful for production environments where logging needs to be more robust and organized across multiple files. It ensures that log files do not grow too large and are easier to manage over time. Adjust the configuration (interval
, path
, custom tokens) as per your application's logging requirements.
Published on: Jun 29, 2024, 03:15 PM