温馨提示×

Debian Nodejs日志级别怎么设

小樊
36
2026-10-13 00:20:42
栏目: 编程语言

在 Debian 上,Node.js 本身的“日志级别”通常不是由系统或 Node 本身统一设置的,而是取决于你用的运行方式和日志框架。下面按常见场景给你说明。


一、Node.js 自身的日志级别(console)

Node.js 没有像 debug / info / warn / error 这种全局日志级别开关,console 永远会输出。

常见做法是:

const logLevel = process.env.LOG_LEVEL || 'info';

function log(level, msg) {
  const levels = { error: 0, warn: 1, info: 2, debug: 3 };
  if (levels[level] <= levels[logLevel]) {
    console[level](msg);
  }
}

运行:

LOG_LEVEL=debug node app.js

二、使用日志库(推荐)

1️⃣ 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

级别:error < warn < info < http < verbose < debug < silly


2️⃣ Pino(性能最好)

const pino = require('pino');
const logger = pino({ level: process.env.LOG_LEVEL || 'info' });
LOG_LEVEL=debug node app.js

3️⃣ Debug 模块

const debug = require('debug')('app');
debug('this is debug');

开启:

DEBUG=app node app.js

三、systemd(Debian 服务方式运行)

如果你是 systemd 启动的 Node 服务:

service 文件示例

[Service]
Environment=LOG_LEVEL=info
ExecStart=/usr/bin/node /opt/app/app.js

重载:

sudo systemctl daemon-reload
sudo systemctl restart yourapp

查看日志:

journalctl -u yourapp -f

四、PM2(常见生产用法)

pm2 start app.js --env production

或:

LOG_LEVEL=debug pm2 restart app

查看:

pm2 logs

五、Nginx / 反向代理日志(补充)

如果你说的是 Web 请求日志级别,那是 Nginx:

error_log /var/log/nginx/error.log warn;

总结

场景 怎么设
原生 console 自己写判断
Winston / Pino LOG_LEVEL 环境变量
debug 模块 DEBUG=*
systemd Environment=
PM2 LOG_LEVEL + restart

如果你能告诉我:

  • 用的是什么框架(Express / Nest / 原生)
  • 怎么运行的(直接 node / systemd / pm2 / docker)

我可以给你精确配置示例。

0 踩