在 Linux 下查看 Node.js 日志,主要看你日志写在哪里、用什么方式运行 Node 程序。下面按常见场景给你一份实用指南。
如果 Node 程序只是用 console.log / console.error,默认输出到:
node app.js
终端里直接看。
如果你用:
node app.js &
或
nohup node app.js &
日志一般在这里:
# nohup 默认
nohup.out
# 或手动重定向
node app.js > app.log 2>&1
查看:
tail -f app.log
pm2 logs
pm2 logs appname
pm2 logs --lines 100
日志文件位置:
~/.pm2/logs/
如果你的 Node 服务是 systemd 管理的:
journalctl -u your-service-name
journalctl -u your-service-name -f
journalctl -u your-service-name --since "10 min ago"
docker logs container_name
docker logs -f container_name
tail -f xxx.log
tail -n 200 xxx.log
grep "ERROR" xxx.log
grep -C 5 "Exception" xxx.log
less xxx.log
# 按 / 搜索,q 退出
winstonpino(性能最好)log4js示例(winston):
const winston = require('winston');
const logger = winston.createLogger({
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
你可以告诉我:
我可以直接给你最合适的命令或配置示例。