在 Linux 环境下配置 Node.js 日志,常见做法包括:
✅ 使用日志库
✅ 配置日志级别
✅ 按日期 / 大小滚动日志文件
✅ 结合 systemd / PM2
✅ 与 Linux 日志系统(rsyslog / journald)对接
下面从 推荐方案 → 进阶方案 → 生产实践 逐步说明。
winston + 文件日志npm install winston
const winston = require('winston');
const path = require('path');
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.printf(({ timestamp, level, message }) => {
return `${timestamp} [${level}]: ${message}`;
})
),
transports: [
new winston.transports.File({ filename: '/var/log/node/app.log' }),
new winston.transports.Console(),
],
});
logger.info('服务启动成功');
logger.error('数据库连接失败');
✅ 优点
⚠️ 注意
/var/log/node 目录需存在且 Node 有写权限sudo mkdir -p /var/log/node
sudo chown -R $(whoami) /var/log/node
winston-daily-rotate-filenpm install winston-daily-rotate-file
const DailyRotateFile = require('winston-daily-rotate-file');
const transport = new DailyRotateFile({
dirname: '/var/log/node',
filename: 'app-%DATE%.log',
datePattern: 'YYYY-MM-DD',
maxSize: '20m',
maxFiles: '14d', // 保留 14 天
});
const logger = winston.createLogger({
transports: [
transport,
new winston.transports.Console(),
],
});
✅ 自动生成:
/var/log/node/app-2026-01-21.log
/var/log/node/app-2026-01-22.log
const level = process.env.NODE_ENV === 'production' ? 'warn' : 'debug';
const logger = winston.createLogger({
level,
transports: [/* ... */],
});
常见级别:
error > warn > info > http > verbose > debug > silly
pm2 start app.js --name my-api
pm2 logs my-api
~/.pm2/logs/
ecosystem.config.js
module.exports = {
apps: [{
name: 'my-api',
script: 'app.js',
error_file: '/var/log/node/err.log',
out_file: '/var/log/node/out.log',
merge_logs: true,
max_memory_restart: '500M',
}]
};
✅ PM2 自动处理:
[Unit]
Description=Node App
After=network.target
[Service]
ExecStart=/usr/bin/node /opt/app/app.js
WorkingDirectory=/opt/app
Restart=always
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
journalctl -u node-app -f
✅ 优点
❌ console.log 直接写文件
node app.js > app.log 2>&1
问题:
| 场景 | 推荐方案 |
|---|---|
| 小型项目 | winston + 文件 |
| 中型项目 | winston + daily-rotate |
| 生产环境 | PM2 + winston |
| 系统级 | systemd + journald |
| 容器 | JSON 日志输出到 stdout |
✅ 不在日志中输出:
✅ 错误日志包括:
✅ 生产环境:
warn 以上如果你愿意,我可以:
你现在的 Node.js 项目是哪种运行方式?