debian

Debian Node.js 日志级别怎么设置

小樊
39
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 应用程序使用第三方日志库,如 winstonpinomorgan。这些库通常提供更灵活的日志级别设置。

使用 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
看了该问题的人还看了