在 Ubuntu 上设置 Node.js 的日志级别,取决于你用的是哪种日志方式(console、Winston、PM2、Docker、systemd 等)。下面按常见场景说明。
Node.js 本身没有“日志级别”概念,console.log/info/warn/error 是写死的。
做法:
console.logconsole.logconst DEBUG = process.env.NODE_ENV !== 'production';
if (DEBUG) console.log('debug info');
npm install winston
const winston = require('winston');
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
transports: [new winston.transports.Console()]
});
LOG_LEVEL=debug node app.js
或写入 .env
LOG_LEVEL=debug
✅ 级别顺序(由低到高):
error < warn < info < http < verbose < debug < silly
PM2 本身不控制应用日志级别,但可配合环境变量:
LOG_LEVEL=debug pm2 start app.js
查看日志:
pm2 logs
如用 Winston:
pm2 restart app --env production
sudo nano /etc/systemd/system/nodeapp.service
[Service]
Environment=LOG_LEVEL=debug
ExecStart=/usr/bin/node /var/www/app/app.js
sudo systemctl daemon-reload
sudo systemctl restart nodeapp
查看日志:
journalctl -u nodeapp -f
ENV LOG_LEVEL=debug
或运行:
docker run -e LOG_LEVEL=debug mynode
| 库 | 设置方式 |
|---|---|
| Winston | level 选项 |
| Pino | level |
| Bunyan | level |
| Morgan | morgan('dev') |
✅ 使用 Winston / Pino
✅ 通过环境变量控制级别
✅ 生产用 info 或 warn
✅ 开发用 debug
如果你愿意,可以告诉我:
我可以直接给你一份可用配置。