在 Debian 上遇到 Node.js 日志不更新,通常不是“Node 自己不写日志”,而是输出被缓冲、被重定向、或服务管理方式导致的。下面按最常见原因给你一个排查清单。
console.log 但日志不实时如果你是这样运行的:
node app.js > app.log 2>&1 &
或者:
nohup node app.js > app.log &
问题原因:
console.log → 使用 块缓冲✅ 表现:
tail -f app.log 很久没内容node app.js | stdbuf -oL -eL tee app.log
或:
stdbuf -oL -eL node app.js >> app.log 2>&1
不要用 console.log 写生产日志:
npm i winston
const winston = require('winston')
const logger = winston.createLogger({
transports: [
new winston.transports.File({ filename: 'app.log' })
]
})
logger.info('hello')
✅ 日志实时写入 ✅ 可控级别 ✅ 可轮转
如果你是用:
systemctl start mynode
journalctl -u mynode -f
而不是你写的 app.log
[Service]
ExecStart=/usr/bin/node /opt/app/app.js
StandardOutput=journal
StandardError=journal
如果你想写文件:
StandardOutput=append:/var/log/node/app.log
StandardError=append:/var/log/node/app.err
ls -i app.log
lsof | grep app.log
✅ 表现:
✅ 解决:
winston + winston-daily-rotate-filetop -p $(pidof node)
✅ 可能原因:
✅ 排查:
node --inspect
或加心跳日志:
setInterval(() => logger.info('alive'), 5000)
ls -l /var/log/node
ps aux | grep node
✅ 解决:
sudo chown -R node:node /var/log/node
请按顺序确认:
console.log + 文件重定向?systemd 管理?journalctl -u 服务名 -f 有日志吗?lsof | grep node 看写哪个文件?如果你愿意,可以把下面信息发我,我可以直接帮你定位:
systemctl cat 你的服务我可以给你精确修复方案。