溫馨提示×

Ubuntu中Node.js日志級別怎么設

小樊
63
2025-04-09 01:26:02
欄目: 編程語言

在Ubuntu系統中,Node.js應用程序的日志級別通常是通過應用程序代碼或配置文件來設置的。以下是一些常見的方法來設置Node.js應用程序的日志級別:

方法一:通過代碼設置

如果你使用的是像winston、morgan或其他日志庫,你可以在代碼中直接設置日志級別。

使用winston

const winston = require('winston');

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

使用morgan

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

const app = express();

app.use(morgan('combined')); // 默認日志級別是combined

// 或者你可以設置特定的日志級別
app.use(morgan('tiny')); // 日志級別為tiny

方法二:通過環境變量設置

許多Node.js應用程序允許通過環境變量來配置日志級別。

使用winston

const winston = require('winston');

const logger = winston.createLogger({
  level: process.env.LOG_LEVEL || 'info', // 從環境變量中讀取日志級別,默認為info
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

你可以在啟動應用程序時設置環境變量:

LOG_LEVEL=debug node app.js

方法三:通過配置文件設置

如果你使用的是像config模塊或其他配置管理工具,你可以在配置文件中設置日志級別。

使用config模塊

const config = require('config');

const logger = winston.createLogger({
  level: config.get('logging.level') || 'info', // 從配置文件中讀取日志級別,默認為info
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

config/default.json中設置日志級別:

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

總結

選擇哪種方法取決于你的具體需求和應用程序的架構。通常,通過代碼或環境變量設置日志級別是最常見和靈活的方法。

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