溫馨提示×

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

小樊
42
2025-10-07 10:00:29
欄目: 編程語言

在Ubuntu系統中,Node.js應用程序的日志級別通常是通過應用程序本身的配置來設置的。大多數Node.js應用程序使用第三方日志庫,如winston、bunyanmorgan等。這些庫通常允許你設置不同的日志級別,例如error、warn、info、http(對于morgan)或debug。

以下是一些常見日志庫的日志級別設置方法:

  1. Winston:

在Winston中,你可以為每個傳輸(transport)設置日志級別。例如,如果你使用consolefile傳輸,可以這樣設置:

const winston = require('winston');

const logger = winston.createLogger({
  level: 'info', // 默認日志級別
  transports: [
    new winston.transports.Console({
      level: 'debug' // 控制臺輸出的日志級別
    }),
    new winston.transports.File({ filename: 'error.log', level: 'error' }), // 只記錄錯誤日志
    new winston.transports.File({ filename: 'combined.log' }) // 記錄所有級別的日志
  ]
});
  1. Bunyan:

在Bunyan中,你可以通過設置stream對象的level屬性來設置日志級別:

const bunyan = require('bunyan');

const logger = bunyan.createLogger({
  name: 'myApp',
  streams: [
    { level: 'info', stream: process.stdout }, // 控制臺輸出的日志級別
    { level: 'error', path: 'error.log' }, // 只記錄錯誤日志
    { level: 'debug', path: 'all.log' } // 記錄所有級別的日志
  ]
});
  1. Morgan:

Morgan是一個HTTP請求記錄中間件,通常用于Express應用程序。你可以通過設置skip函數來自定義日志級別:

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

const app = express();

// 只記錄4xx和5xx錯誤
morgan.token('status', (req, res) => {
  if (res.statusCode >= 400) {
    return res.statusCode;
  }
  return '-';
});

app.use(morgan(':method :url :status :res[content-length] - :response-time ms', { skip: (req, res) => res.statusCode < 400 }));

app.listen(3000);

請根據你的應用程序使用的日志庫進行相應的調整。如果你不確定使用的是哪個庫,請查看應用程序的依賴項或源代碼。

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