在 Debian 下配置 Node.js 日志,一般可以从 应用层日志(代码里)、系统层日志(systemd / journald)、日志轮转(logrotate) 三个方面来做。下面按常见场景说明。
不要直接用 console.log 上生产。
常用库:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: '/var/log/nodejs/app.log' }),
new winston.transports.File({ filename: '/var/log/nodejs/error.log', level: 'error' })
]
});
logger.info('server started');
logger.error('db connect failed');
如果你用 systemd 管理 Node.js 服务(推荐):
sudo nano /etc/systemd/system/nodeapp.service
示例:
[Unit]
Description=Node.js App
After=network.target
[Service]
User=node
WorkingDirectory=/opt/nodeapp
ExecStart=/usr/bin/node /opt/nodeapp/app.js
Restart=on-failure
StandardOutput=journal
StandardError=journal
SyslogIdentifier=nodeapp
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl start nodeapp
sudo systemctl enable nodeapp
journalctl -u nodeapp
journalctl -u nodeapp -f
journalctl -u nodeapp --since "1 hour ago"
✅ 优点:
journald 有大小限制如果你 Node 写文件日志:
sudo nano /etc/logrotate.d/nodeapp
示例:
/var/log/nodejs/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
copytruncate
}
测试:
sudo logrotate -d /etc/logrotate.d/nodeapp
⚠️ copytruncate 对 Node 很重要,否则文件句柄不会释放。
修改:
sudo nano /etc/systemd/journald.conf
SystemMaxUse=500M
SystemKeepFree=100M
MaxRetentionSec=2week
sudo systemctl restart systemd-journald
✅ 最佳实践
winston / pinosystemdjournaldlogrotate + copytruncate如果你愿意,可以告诉我:
我可以给你一套 可直接用的配置模板。