溫馨提示×

centos中nodejs日志級別怎么設置

小樊
61
2025-02-18 22:21:00
欄目: 編程語言

在CentOS系統中,Node.js應用程序的日志級別通常是通過應用程序本身的配置來設置的,而不是通過操作系統級別的設置。以下是一些常見的方法來設置Node.js應用程序的日志級別:

1. 使用環境變量

許多Node.js日志庫(如winston、morgan等)支持通過環境變量來設置日志級別。

示例:使用winston

const winston = require('winston');

const logger = winston.createLogger({
  level: process.env.LOG_LEVEL || 'info', // 默認日志級別為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' })
  ]
});

// 設置日志級別
process.env.LOG_LEVEL = 'debug'; // 可以在運行時更改日志級別

2. 使用配置文件

你也可以通過配置文件來設置日志級別。

示例:使用config模塊

const config = require('config');
const winston = require('winston');

const logger = winston.createLogger({
  level: config.get('logging.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' })
  ]
});

配置文件config/default.json

{
  "logging": {
    "level": "info"
  }
}

3. 在代碼中直接設置

你也可以在代碼中直接設置日志級別。

示例:使用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.level = 'debug';

4. 使用PM2管理日志級別

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

示例:PM2配置文件ecosystem.config.js

module.exports = {
  apps: [{
    name: 'my-app',
    script: 'app.js',
    env: {
      NODE_ENV: 'development',
      LOG_LEVEL: 'debug' // 設置日志級別
    },
    env_production: {
      NODE_ENV: 'production',
      LOG_LEVEL: 'info' // 生產環境日志級別
    }
  }]
};

然后使用PM2啟動應用程序:

pm2 start ecosystem.config.js --env production

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

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