发布于2026-07-17 阅读(0)
扫一扫,手机访问
在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这类成熟库,少踩坑。
上一篇:如何用grep查找Node日志
下一篇:如何用脚本自动化处理Node日志
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8