Log File Rotation in Node.js with Express
Log file rotation in Node.js is essential for managing log size and ensuring efficient monitoring of your application. In this guide, we will implement log file rotation in a Node.js application using Express and the winston
and winston-daily-rotate-file
packages.
Step 1: Set Up Express for Logging
First, create a basic Express app:
Initialize the project:
mkdir log-rotation-demo cd log-rotation-demo npm init -y
Install Express:
npm install express
Create an index.js file:
// index.js const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Welcome to the Log Rotation Demo!'); }); app.listen(3000, () => { console.log('Server running on port 3000'); });
Start the server using:
node index.js
Step 2: Configure Winston Logger for Log File Rotation
Install Winston and the rotation package:
npm install winston winston-daily-rotate-file
Configure Winston with log rotation: Create a new file named logger.js
:
// logger.js const { createLogger, format, transports } = require('winston'); require('winston-daily-rotate-file'); const transport = new (transports.DailyRotateFile)({ filename: 'logs/application-%DATE%.log', datePattern: 'YYYY-MM-DD', zippedArchive: true, maxSize: '20m', maxFiles: '14d', }); const logger = createLogger({ level: 'info', format: format.combine( format.timestamp(), format.json() ), transports: [transport], }); module.exports = logger;
Step 3: Integrate Log File Rotation with Express
Use the logger in index.js
:
// index.js const express = require('express'); const logger = require('./logger'); // Import the logger const app = express(); app.use((req, res, next) => { logger.info(`Incoming request: ${req.method} ${req.url}`); next(); }); app.get('/', (req, res) => { logger.info('Handled root endpoint'); res.send('Welcome to the Log Rotation Demo!'); }); app.listen(3000, () => { logger.info('Server running on port 3000'); });
Conclusion:
Now, your application is equipped with log file rotation! It automatically creates daily log files, compresses them, and retains logs for 14 days. This setup ensures efficient log management, making it easier to monitor your Node.js application.