溫馨提示×

Debian Node.js 日志級別怎么設置

小樊
54
2025-04-11 13:09:32
欄目: 編程語言

在 Debian 系統上,Node.js 應用程序的日志級別通常由應用程序本身或使用的日志庫來控制。以下是一些常見的方法來設置 Node.js 應用程序的日志級別:

1. 使用內置的 console 模塊

如果你使用的是 Node.js 內置的 console 模塊來記錄日志,可以通過調整日志消息的級別來控制輸出。例如:

console.log('This is a log message'); // 默認級別
console.info('This is an info message'); // 信息級別
console.warn('This is a warning message'); // 警告級別
console.error('This is an error message'); // 錯誤級別

2. 使用第三方日志庫

許多 Node.js 應用程序使用第三方日志庫,如 winston、pinomorgan。這些庫通常提供更靈活的日志級別設置。

使用 winston

winston 是一個流行的日志庫,可以通過配置來設置日志級別:

const winston = require('winston');

const logger = winston.createLogger({
  level: 'info', // 設置默認日志級別
  format: winston.format.json(),
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

logger.info('This is an info message');
logger.error('This is an error message');

使用 pino

pino 是另一個高性能的日志庫,也可以通過配置來設置日志級別:

const pino = require('pino');
const logger = pino({
  level: 'info' // 設置默認日志級別
});

logger.info('This is an info message');
logger.error('This is an error message');

3. 配置環境變量

有些日志庫允許通過環境變量來設置日志級別。例如,winston 可以通過環境變量 WINSTON_LEVEL 來設置:

export WINSTON_LEVEL=info
node your-app.js

4. 使用 PM2 管理 Node.js 應用程序

如果你使用 PM2 來管理 Node.js 應用程序,可以通過 PM2 的配置文件來設置日志級別:

{
  "apps": [
    {
      "name": "your-app",
      "script": "your-app.js",
      "env": {
        "NODE_ENV": "production",
        "LOG_LEVEL": "info"
      }
    }
  ]
}

然后在你的應用程序中使用環境變量來設置日志級別:

const winston = require('winston');

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

logger.info('This is an info message');

通過這些方法,你可以在 Debian 系統上靈活地設置 Node.js 應用程序的日志級別。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女