在 Linux 上 Node.js 日志不输出 是很常见的问题,通常不是 Node 本身不打印,而是输出目标、缓冲、权限或进程管理方式导致的。下面按最常见原因逐一说明。
Node 中:
console.log → stdoutconsole.error / 抛出异常 → stderr如果你这样运行:
node app.js > out.log
那 console.error 是看不到的,需要:
node app.js > out.log 2>&1
pm2 logs
或
~/.pm2/logs/
nohup node app.js &
日志在:
nohup.out
不是直接打印到终端,而是:
journalctl -u your-service
在 非 TTY 环境(管道、文件、后台进程) 中:
console.log 是行缓冲\n,可能不会立即输出✅ 解决方式:
process.stdout.write("log\n");
或
console.log("log");
比如:
throw new Error("xx");
process.exit(1);
如果 exit 在 throw 前,日志不会出来。
✅ 推荐:
process.on('uncaughtException', e => {
console.error(e);
process.exit(1);
});
fs.writeFileSync('/var/log/app.log', 'x');
可能:
✅ 检查:
whoami
ls -ld /var/log
如:
示例(winston 忘记加 console):
logger.add(new transports.File({ filename: 'a.log' }));
→ 终端什么都没有
Node 在 Docker 默认:
但如果:
node app.js > app.log
那就看不到了
✅ Docker 正确方式:
node app.js
# 1. 看 stdout + stderr
node app.js 2>&1 | tee log.txt
# 2. 检查是否真的执行到日志
console.log("START");
# 3. 用 systemd / pm2 看日志
journalctl -u xxx
pm2 logs
# 4. 强制刷新
process.stdout.write("test\n");
你可以贴一下:
console.log 还是文件)我可以直接告诉你为什么没输出 + 改哪一行。