在 Linux 下 JS(Node.js / 前端 / Electron 等)日志“丢失”,通常不是真的没产生,而是没写进去、被覆盖、被缓冲、被重定向错了位置或权限不足。下面按常见原因系统说明。
很多 JS 程序用:
console.log(...)
console.error(...)
但 Linux 下:
node app.js > /dev/null 2>&1
或
nohup node app.js &
日志会:
✅ 检查:
ps aux | grep node
lsof -p <pid>
Node.js 的 console.log 在:
会异步缓冲,进程异常退出时:
缓冲区没写盘 → 日志“丢失”
✅ 解决:
process.stdout.write(log + "\n")
常见组合:
现象:
✅ 检查:
ls -l /proc/<pid>/fd
✅ 正确方式:
winston / pinoJS 进程用户无写权限:
EACCES: permission denied
但:
✅ 检查:
ls -l 日志目录
whoami
Docker 默认:
如果你:
fs.writeFileSync('/var/log/app.log')
但:
日志直接消失
✅ 正确方式:
docker logs <container>
或挂载 volume
PM2 默认日志在:
~/.pm2/logs
但:
✅ 查看:
pm2 logs
pm2 describe <id>
process.on('uncaughtException')
process.on('unhandledRejection')
没监听 → 进程直接死 → 最后日志没写
✅ 必须加:
process.on('uncaughtException', e => {
console.error(e);
process.exit(1);
});
npm i winston
const winston = require('winston');
winston.add(new winston.transports.File({ filename: 'app.log' }));
优点:
> /dev/null?如果你愿意,可以告诉我:
我可以精准定位你这个“丢失”是哪一类。