在 Ubuntu 上 Node.js 日志为空,通常不是 Node 本身的问题,而是日志没有真正输出到你认为的地方。下面按最常见原因逐条排查,你可以对照看看属于哪一种。
确认进程是否真的在跑:
ps aux | grep node
或:
systemctl status your-service
如果进程没启动或反复重启,自然不会有日志。
Node.js 默认日志是:
console.log() // stdout
console.error() // stderr
如果你用:
node app.js
但没有重定向,日志可能:
✅ 正确查看方式:
journalctl -u your-service -f
或(PM2):
pm2 logs
如果你用 systemd 启动 Node:
[Service]
ExecStart=/usr/bin/node /app/app.js
✅ 日志不会写到文件,而是在 journald 里。
查看:
journalctl -u your-service -f
如果你期望日志写到文件,必须显式指定:
StandardOutput=append:/var/log/node/app.log
StandardError=append:/var/log/node/error.log
并确保目录存在:
mkdir -p /var/log/node
chown -R youruser:youruser /var/log/node
如果你用 PM2 启动:
pm2 start app.js
日志在这里:
pm2 logs
pm2 logs app
而不是:
/var/log/*
PM2 默认日志路径:
~/.pm2/logs/
如果你用的是日志库:
winston.createLogger({
transports: [
new winston.transports.File({ filename: 'app.log' })
]
})
⚠️ 相对路径是相对于启动目录,不是 JS 文件。
确认实际路径:
console.log(process.cwd())
✅ 建议用绝对路径:
path.join(__dirname, 'logs/app.log')
如果你在 Docker 里:
✅ 正确方式:
console.log('hello')
查看:
docker logs <container-id>
例如:
level: 'error'
那 info 日志就不会出现。
✅ 临时测试:
logger.info('test')
logger.error('test')
日志文件存在,但 Node 没权限写:
ls -l /var/log/node/app.log
解决:
chmod 644 /var/log/node/app.log
chown node:node /var/log/node/app.log
# 1. 进程在跑吗?
ps aux | grep node
# 2. 用 systemd?
journalctl -u your-service -f
# 3. 用 PM2?
pm2 logs
# 4. 有 console.log 吗?
node -e "console.log('hello')"
你可以直接贴出:
我可以一步一步帮你把日志“找回来”。