在 Debian 上运行 Node.js 时日志“丢失”,通常不是真的消失了,而是输出方式、systemd、管道、日志轮转或权限等问题导致的。下面按最常见原因 → 排查方法 → 解决办法来说明。
console.log,但被 systemd / 容器吞掉如果你用 systemd 管理 Node.js 服务:
[Service]
ExecStart=/usr/bin/node /app/server.js
✅ console.log 不会写文件
✅ 默认输出到 journald
❌ 如果你没配置,很容易“看起来没日志”
journalctl -u your-service-name -f
✅ 显式输出到 stdout / stderr(推荐):
console.log('info')
console.error('error')
✅ 或写文件:
const fs = require('fs')
fs.appendFileSync('/var/log/node/app.log', msg + '\n')
Node.js 输出是 行缓冲,但 systemd 有时会延迟显示。
[Service]
StandardOutput=journal
StandardError=journal
或:
StandardOutput=append:/var/log/node/app.log
StandardError=append:/var/log/node/error.log
Debian 默认:
nobody / www-data 运行/var/log 只有 root 可写sudo mkdir -p /var/log/node
sudo chown -R www-data:www-data /var/log/node
Debian 常见 /etc/logrotate.d/
如果配置错误:
/var/log/node/*.log {
daily
truncate
}
copytruncate
或让 Node 重新打开文件(推荐用 PM2 / winston)
如果你用 PM2:
pm2 logs
pm2 logs app-name
PM2 默认日志在:
~/.pm2/logs/
✅ 很容易误以为“日志丢了”
在 Docker + Debian 中:
console.log 必须输出到 stdout✅ 正确:
console.log('hello')
❌ 错误:
fs.writeFileSync('/app/log.txt', '...')
process.on('uncaughtException', err => {
console.error(err)
})
常见错误:
error,info 不显示请逐条确认:
console.log?journalctl?✅ 标准组合
✅ 示例 systemd
[Service]
ExecStart=/usr/bin/node /app/index.js
StandardOutput=append:/var/log/node/app.log
StandardError=append:/var/log/node/error.log
Restart=always
你可以直接贴出:
我可以 直接告诉你哪一行导致日志丢失。