Welcome to this comprehensive guide on Log Rotation in Node.js! In this tutorial, we'll learn what log rotation is, why it's important, and how to implement it in our Node.js applications. 🎯
Log rotation is the process of managing log files in such a way that they don't grow indefinitely. This is essential for maintaining system performance and managing storage resources.
In the context of Node.js, log files are used to store error messages, warnings, and other important information during the execution of our applications.
Node.js provides several libraries for log rotation, but we'll be using winston – a popular and powerful logging library.
First, we need to install winston using npm (Node Package Manager):
npm install winstonNow, let's create a new file called app.js and set up Winston:
const winston = require('winston');
// Create the loggers
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'app.log', maxsize: 5242880, maxFiles: 5, tailable: false }) // Daily rotation with max 5MB files and 5 rotations
]
});
// Log information
function logInfo(message) {
logger.info(message);
}
// Log error
function logError(error) {
logger.error(error);
}
// Log custom events
function logCustomEvent(event, data) {
logger.log({ level: event, message: data });
}In this example, we've set up a basic logger with daily rotation, limiting log files to 5MB and keeping 5 rotated files. The logInfo, logError, and logCustomEvent functions can be used to log information, errors, and custom events, respectively.
Now, let's use our logger in a simple Node.js server:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello, World!');
});
server.listen(3000, () => {
logInfo(`Server started on port 3000`);
});This simple server will log a message when it starts. With Winston, you can also log errors and custom events as needed.
To test log rotation, you can run the application multiple times and inspect the log files. After 5 logs, the first log file (app.log) should be rotated, and a new one (app-2022-10-12.log) should be created.
What is the purpose of log rotation in Node.js?
We hope you found this tutorial helpful! As you continue to work with Node.js, log rotation will become an essential tool for maintaining your applications' performance and managing storage resources. Happy coding! 🎯