Log Rotation — Managing Log Files with Rotation Strategies
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you'll learn about Log Rotation. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Log rotation prevents disk space exhaustion by archiving, compressing, and deleting old log files according to policy.
// Programmatic log rotation
const fs = require('fs');
const zlib = require('zlib');
class LogRotationManager {
constructor(options = {}) {
this.logDir = options.logDir || '/var/log/scanapp';
this.maxSize = options.maxSize || 100 * 1024 * 1024; // 100MB
this.maxFiles = options.maxFiles || 10;
this.compression = options.compression !== false;
this.pattern = options.pattern || 'app-*.log';
}
async checkAndRotate(logger) {
const files = await this.getLogFiles();
for (const file of files) {
const stats = fs.statSync(file);
if (stats.size >= this.maxSize) {
await this.rotateFile(file);
}
}
// Remove old files
const allFiles = await this.getLogFiles();
if (allFiles.length > this.maxFiles) {
const sorted = allFiles.sort((a, b) => fs.statSync(a).mtimeMs - fs.statSync(b).mtimeMs);
const toRemove = sorted.slice(0, sorted.length - this.maxFiles);
for (const file of toRemove) {
fs.unlinkSync(file);
logger.info(`Removed old log file: ${file}`);
}
}
}
async rotateFile(filePath) {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const rotatedPath = `${filePath}.${timestamp}`;
fs.renameSync(filePath, rotatedPath);
fs.writeFileSync(filePath, ''); // Create new empty log
if (this.compression) {
await this.compressFile(rotatedPath);
}
}
async compressFile(filePath) {
const content = fs.readFileSync(filePath);
const compressed = zlib.gzipSync(content);
fs.writeFileSync(`${filePath}.gz`, compressed);
fs.unlinkSync(filePath);
}
async getLogFiles() {
const files = fs.readdirSync(this.logDir);
const pattern = new RegExp('^' + this.pattern.replace('*', '.*') + '$');
return files
.filter(f => pattern.test(f))
.map(f => `${this.logDir}/${f}`)
.filter(f => fs.statSync(f).isFile());
}
}
// Winston daily rotation
const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
const logger = winston.createLogger({
transports: [
new DailyRotateFile({
filename: 'app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
maxSize: '100m',
maxFiles: '14d',
zippedArchive: true
})
]
});
Automated log rotation prevents disk full incidents while maintaining accessible log history for debugging.
← Previous
Database Query Logging — Logging and Monitoring Database Queries
Next →
Log Shipping — Reliable Log Transport from Services to Central Storage
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro