ubuntu

如何设置Node.js日志级别在Ubuntu上

小樊
63
2025-08-08 22:20:29
栏目: 编程语言

在Ubuntu上设置Node.js应用程序的日志级别通常涉及修改应用程序的代码或配置文件,或者调整日志库的设置。以下是一些常见的方法:

方法一:修改代码

如果你使用的是像winstonmorgan这样的日志库,你可以在代码中直接设置日志级别。

使用winston

const winston = require('winston');

const logger = winston.createLogger({
  level: 'info', // 设置日志级别
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

使用morgan

const morgan = require('morgan');
const express = require('express');
const app = express();

app.use(morgan('combined')); // 默认日志级别是 'combined'

方法二:使用环境变量

许多日志库支持通过环境变量来设置日志级别。

使用winston

const winston = require('winston');

const logger = winston.createLogger({
  level: process.env.LOG_LEVEL || 'info', // 从环境变量读取日志级别
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

你可以在启动应用程序之前设置环境变量:

export LOG_LEVEL=debug
node app.js

使用morgan

const morgan = require('morgan');
const express = require('express');
const app = express();

app.use(morgan(process.env.LOG_LEVEL || 'combined')); // 从环境变量读取日志级别

同样,你可以在启动应用程序之前设置环境变量:

export LOG_LEVEL=combined
node app.js

方法三:配置文件

如果你使用的是配置文件来管理应用程序的设置,你可以在配置文件中设置日志级别。

使用config

假设你有一个config目录,其中包含不同环境的配置文件(如default.json, development.json, production.json)。

// config/development.json
{
  "logging": {
    "level": "debug"
  }
}

在代码中读取配置文件:

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.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

方法四:使用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 start ecosystem.config.js --env development

通过这些方法,你可以在Ubuntu上灵活地设置Node.js应用程序的日志级别。选择哪种方法取决于你的具体需求和项目结构。

0
看了该问题的人还看了