在 Debian 上,Node.js 本身的“日志级别”通常不是由系统或 Node 本身统一设置的,而是取决于你用的运行方式和日志框架。下面按常见场景给你说明。
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
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
const pino = require('pino');
const logger = pino({ level: process.env.LOG_LEVEL || 'info' });
LOG_LEVEL=debug node app.js
const debug = require('debug')('app');
debug('this is debug');
开启:
DEBUG=app node app.js
如果你是 systemd 启动的 Node 服务:
[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 start app.js --env production
或:
LOG_LEVEL=debug pm2 restart app
查看:
pm2 logs
如果你说的是 Web 请求日志级别,那是 Nginx:
error_log /var/log/nginx/error.log warn;
| 场景 | 怎么设 |
|---|---|
| 原生 console | 自己写判断 |
| Winston / Pino | LOG_LEVEL 环境变量 |
| debug 模块 | DEBUG=* |
| systemd | Environment= |
| PM2 | LOG_LEVEL + restart |
如果你能告诉我:
我可以给你精确配置示例。