centos中nodejs日志级别怎么设置

731
2025/2/19 0:32:29
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在CentOS系统中,Node.js应用程序的日志级别通常是通过应用程序本身的配置来设置的,而不是通过操作系统级别的设置。以下是一些常见的方法来设置Node.js应用程序的日志级别:

1. 使用环境变量

许多Node.js日志库(如winstonmorgan等)支持通过环境变量来设置日志级别。

示例:使用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应用程序的日志级别。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: centos dhcpclient如何配置