温馨提示×

ubuntu nodejs日志级别怎么设

小樊
39
2026-10-03 13:39:46
栏目: 编程语言

在 Ubuntu 上设置 Node.js 的日志级别,取决于你用的是哪种日志方式(console、Winston、PM2、Docker、systemd 等)。下面按常见场景说明。


一、使用 console(最基础)

Node.js 本身没有“日志级别”概念,console.log/info/warn/error 是写死的。

做法:

  • 开发:console.log
  • 生产:减少 console.log
const DEBUG = process.env.NODE_ENV !== 'production';

if (DEBUG) console.log('debug info');

二、使用 Winston(最常见)

1️⃣ 安装

npm install winston

2️⃣ 设置日志级别

const winston = require('winston');

const logger = winston.createLogger({
  level: process.env.LOG_LEVEL || 'info',
  transports: [new winston.transports.Console()]
});

3️⃣ Ubuntu 启动设置级别

LOG_LEVEL=debug node app.js

或写入 .env

LOG_LEVEL=debug

✅ 级别顺序(由低到高):

error < warn < info < http < verbose < debug < silly

三、使用 PM2(Ubuntu 常用)

PM2 本身不控制应用日志级别,但可配合环境变量:

LOG_LEVEL=debug pm2 start app.js

查看日志:

pm2 logs

如用 Winston:

pm2 restart app --env production

四、使用 systemd(Ubuntu 服务)

1️⃣ 编辑服务

sudo nano /etc/systemd/system/nodeapp.service

2️⃣ 添加环境变量

[Service]
Environment=LOG_LEVEL=debug
ExecStart=/usr/bin/node /var/www/app/app.js

3️⃣ 重载

sudo systemctl daemon-reload
sudo systemctl restart nodeapp

查看日志:

journalctl -u nodeapp -f

五、Docker + Ubuntu

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


如果你愿意,可以告诉我:

  • 用的 日志库(Winston / Pino / 原生)
  • 启动方式(PM2 / systemd / Docker)
  • Ubuntu 版本

我可以直接给你一份可用配置。

0 踩