Node.js日志归档可用winston库实现日志分割、压缩、按天轮转及保留天数控制;也可用fs模块手工实现,但需自行处理日期比较与文件重命名,且易出错。生产环境推荐使用winston等成熟方案,稳定可靠。
在Node.js开发中,日志归档是常见需求——日志文件无限制膨胀会导致磁盘空间耗尽。无论是借助第三方库还是使用Node自带模块,实现日志归档并不复杂。以下提供两种实用方案。

长期稳定更新的攒劲资源: >>>点此立即查看<<<
winston库实现日志归档如果接受第三方库,winston是社区中成熟的解决方案之一。它内置日志分割、压缩、保留天数等功能,无需自行开发轮子。
安装步骤:
npm install winston
创建logger.js文件,配置归档逻辑:
const winston = require('winston');
const { combine, timestamp, printf } = winston.format;
// 自定义日志格式
const myFormat = printf(({ level, message, timestamp }) => {
return `${timestamp} ${level.toUpperCase()}: ${message}`;
});
// 创建logger实例
const logger = winston.createLogger({
level: 'info',
format: combine(timestamp(), myFormat),
transports: [
new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
new winston.transports.File({ filename: 'logs/combined.log' }),
],
});
// 日志归档核心:按天轮转
const archive = new winston.transports.DailyRotateFile({
filename: 'logs/logs-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true, // 压缩历史日志
maxSize: '20m', // 单个文件大小上限
maxFiles: '14d', // 保留14天内的日志
});
logger.add(archive);
module.exports = logger;
使用时直接引入:
const logger = require('./logger');
logger.info('Hello, world!');
配置后,日志自动按天生成文件,旧日志压缩归档,超过14天自动清理——实现“开箱即用”的效果。
fs模块手动实现日志归档若不引入第三方依赖,Node自带的fs模块配合moment(也可用原生Date替代)即可完成归档。以下是一个简单完整的实现:
const fs = require('fs');
const path = require('path');
const os = require('os');
const moment = require('moment'); // 若不想引入moment,可用Date自行处理格式化
const logDir = path.join(__dirname, 'logs');
const archiveDir = path.join(logDir, 'archive');
// 确保目录存在
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}
if (!fs.existsSync(archiveDir)) {
fs.mkdirSync(archiveDir);
}
const logFile = path.join(logDir, 'app.log');
const archiveLogFile = path.join(archiveDir, `app-${moment().format('YYYY-MM-DD')}.log`);
function logToFile(message) {
const timestamp = moment().format('YYYY-MM-DD HH:mm:ss');
const logEntry = `${timestamp}: ${message}\n`;
fs.appendFile(logFile, logEntry, (err) => {
if (err) console.error('Error writing to log file:', err);
});
// 每日归档:若当前日期与前一日不同,将旧日志移至归档目录
if (moment().format('YYYY-MM-DD') !== moment().subtract(1, 'days').format('YYYY-MM-DD')) {
fs.rename(logFile, archiveLogFile, (err) => {
if (err) console.error('Error archiving log file:', err);
});
}
}
logToFile('Hello, world!');
此方案轻量可控,但需自行处理日期比较、文件重命名、并发写入等问题。若项目规模较小或对第三方依赖有严格限制,手工实现足够使用。生产环境建议使用winston等成熟库,以减少潜在问题。
侠游戏发布此文仅为了传递信息,不代表侠游戏网站认同其观点或证实其描述