Comprehensive Guide to Rotating File Stream for Node.js Logging

Introduction to Rotating File Stream in Node.js

The rotating-file-stream library is an excellent tool for handling log rotation in Node.js applications. It allows the creation of a new log file at various intervals, ensuring that the log files remain manageable and easier to process. This guide delves into the usage of rotating-file-stream along with several of its APIs and practical code snippets.

Getting Started


// Install rotating-file-stream
npm install rotating-file-stream

Basic Usage


const rfs = require('rotating-file-stream');

// Create a rotating file stream
const logStream = rfs.createStream('logfile.log', {
  size: '10M', // rotate every 10 MegaBytes written
  interval: '1d', // rotate daily
  compress: 'gzip' // compress the rotated files
});

logStream.write('This is a log message.');

Advanced Usage

You can use more advanced options provided by rotating-file-stream to achieve complex logging mechanisms.

Using a Custom Rotator Function


const logStream = rfs.createStream('logfile.log', {
  size: '10M',
  interval: '1d',
  compress: 'gzip',
  path: '/path/to/logdirectory', // specify custom log directory
  rotate: 7, // keep 7 back copies only
  maxFiles: 30 // total max number of files
});

Stream Options


const logStream = rfs.createStream('logfile.log', {
  size: '10M',
  interval: '1d',
  compress: 'gzip',
  maxFiles: 10,
  maxSize: '50M',
  path: 'my_logs'
});

These options allow for further customization of your log file handling.

Application Example with Express.js

Below is a simple example of integrating rotating-file-stream with an Express.js application.


const express = require('express');
const rfs = require('rotating-file-stream');
const morgan = require('morgan');
const path = require('path');

const app = express();
const port = 3000;

// Create a rotating write stream
const logDirectory = path.join(__dirname, 'log');
const accessLogStream = rfs.createStream('access.log', {
  interval: '1d', // Rotate daily
  path: logDirectory
});

// Setup the logger
app.use(morgan('combined', { stream: accessLogStream }));

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

app.listen(port, () => {
  console.log(`App running at http://localhost:${port}`);
});

Conclusion

Using rotating-file-stream in Node.js applications makes log management straightforward and efficient. It ensures your applications maintain a clean, organized log system.

Hash: 7a08aac387ed5aaedd891b20c276b3324b8a2070dda4682e3b60a92a7d5cded3

Leave a Reply

Your email address will not be published. Required fields are marked *