在Ubuntu系統中,Node.js應用程序的日志級別通常是通過應用程序本身的配置來設置的。大多數Node.js應用程序使用第三方日志庫,如winston、bunyan或morgan等。這些庫通常允許你設置不同的日志級別,例如error、warn、info、http(對于morgan)或debug。
以下是一些常見日志庫的日志級別設置方法:
在Winston中,你可以為每個傳輸(transport)設置日志級別。例如,如果你使用console和file傳輸,可以這樣設置:
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' }) // 記錄所有級別的日志
]
});
在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' } // 記錄所有級別的日志
]
});
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);
請根據你的應用程序使用的日志庫進行相應的調整。如果你不確定使用的是哪個庫,請查看應用程序的依賴項或源代碼。