在Ubuntu系統中,Node.js應用程序的日志級別通常是通過應用程序本身的配置來設置的。大多數Node.js應用程序使用第三方日志庫,如winston
、morgan
或bunyan
等。這些庫允許你根據需要設置不同的日志級別。
以下是一些常見日志庫的日志級別設置方法:
在Winston中,你可以為每個傳輸(transport)設置不同的日志級別。例如,如果你想要將控制臺輸出的日志級別設置為info
,可以這樣配置:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info', // 默認日志級別
format: winston.format.json(),
transports: [
new winston.transports.Console({
level: 'info' // 控制臺輸出日志級別
})
]
});
Morgan是一個HTTP請求記錄器中間件,用于Express應用程序。你可以通過設置環境變量MORGAN_LOG_LEVEL
來更改日志級別:
export MORGAN_LOG_LEVEL=info
或者在你的Express應用程序中直接設置:
const express = require('express');
const morgan = require('morgan');
const app = express();
app.use(morgan('combined', { stream: { write: message => console.log(message.trim()) }, skip: (req, res) => false }));
app.set('env', 'development'); // 設置環境變量MORGAN_LOG_LEVEL為'develop'
在Bunyan中,你可以在創建日志記錄器時設置日志級別:
const bunyan = require('bunyan');
const logger = bunyan.createLogger({
name: 'myApp',
level: 'info' // 設置日志級別
});
請注意,這些示例僅適用于相應的日志庫。你需要根據你的應用程序使用的日志庫進行相應的調整。同時,確保在部署到生產環境之前,將日志級別設置為適當的值,以避免泄露敏感信息。