Introduction to rotating-file-stream
The rotating-file-stream is a robust logging utility designed to handle log rotation in a variety of configurations. This tool is indispensable for managing log files efficiently, especially for applications that generate a substantial amount of log data. In this article, we’ll delve into the numerous APIs provided by rotating-file-stream, complete with code snippets and an actual app example to help you implement these features seamlessly.
Basic Setup
const rfs = require('rotating-file-stream'); const path = require('path'); // Create a rotating write stream const stream = rfs.createStream('access.log', { interval: '1d', // rotate daily path: path.join(__dirname, 'log') });
Advanced Configuration
Customize your log rotation using various options:
const stream = rfs.createStream('access.log', { size: '10M', // rotate every 10 MegaBytes written interval: '1d', // rotate daily compress: 'gzip', // compress rotated files path: path.join(__dirname, 'log') });
Managing History
Configure the number of old log files to keep using the maxFiles
option:
const stream = rfs.createStream('access.log', { interval: '1d', path: path.join(__dirname, 'log'), maxFiles: 7 // keep up to 7 log files });
Using Asynchronous Rotation
Handle log rotation asynchronously for better performance:
const stream = rfs.createStream('access.log', { interval: '1d', path: path.join(__dirname, 'log'), rotate: 2 // rotate existing file based on the rotated count });
Example Application
Here’s an example of integrating rotating-file-stream with an Express.js application:
const express = require('express'); const rfs = require('rotating-file-stream'); const path = require('path'); const morgan = require('morgan'); const app = express(); // Setup rotating logging stream const accessLogStream = rfs.createStream('access.log', { interval: '1d', path: path.join(__dirname, 'log'), compress: 'gzip', maxFiles: 7 }); // Setup morgan logger to use the rotating stream app.use(morgan('combined', { stream: accessLogStream })); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
With the example above, your application will log HTTP requests into daily rotated files, compress the older log files, and keep up to 7 history files.
Conclusion
The rotating-file-stream library is a versatile and powerful tool for managing log files in Node.js applications. By leveraging its features, you can ensure efficient log rotation, better disk space management, and improved performance for your application.
Hash: 7a08aac387ed5aaedd891b20c276b3324b8a2070dda4682e3b60a92a7d5cded3