Introduction to winston-daily-rotate-file
winston-daily-rotate-file is a transport for the winston logging library that allows you to log messages and automatically manage them by rotating the log files daily. This is crucial for managing log files efficiently without letting them grow indefinitely, which can lead to performance issues.
Setting Up winston-daily-rotate-file
To use winston-daily-rotate-file, you need to install it along with winston:
npm install winston winston-daily-rotate-file
Basic Usage
Here is a basic example of how to set up and use winston-daily-rotate-file:
const winston = require('winston');
require('winston-daily-rotate-file');
const transport = new winston.transports.DailyRotateFile({
filename: 'application-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d'
});
const logger = winston.createLogger({
transports: [
transport
]
});
logger.info('Hello, this is a single log message!');
Advanced Configuration
winston-daily-rotate-file provides many options for more advanced configurations.
Custom Log Level
const transport = new winston.transports.DailyRotateFile({
filename: 'application-%DATE%.log',
datePattern: 'YYYY-MM-DD',
level: 'error'
});
Handling Exceptions
const transport = new winston.transports.DailyRotateFile({
filename: 'application-%DATE%-exceptions.log',
datePattern: 'YYYY-MM-DD',
handleExceptions: true
});
Custom Timestamp Format
const transport = new winston.transports.DailyRotateFile({
filename: 'application-%DATE%.log',
datePattern: 'YYYY-MM-DD-HH',
timestamp: function() {
return new Date().toString();
}
});
JSON Log Format
const transport = new winston.transports.DailyRotateFile({
filename: 'application-%DATE%.log',
datePattern: 'YYYY-MM-DD',
format: winston.format.json()
});
Application Example
Below is an example of an Express application that uses winston-daily-rotate-file for logging:
const express = require('express');
const winston = require('winston');
require('winston-daily-rotate-file');
const app = express();
const transport = new winston.transports.DailyRotateFile({
filename: 'app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d'
});
const logger = winston.createLogger({
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
transport
]
});
app.use((req, res, next) => {
logger.info(`${req.method} ${req.url}`);
next();
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Application is running on port 3000');
});
With these configurations and examples, you can efficiently manage your log files using winston-daily-rotate-file.
Hash: d5630d07c5a379090081eddf066b627216849a82b48bd7c00525ceedddd16751