在 Debian 系統上,Node.js 應用程序的日志級別通常由應用程序本身或使用的日志庫來控制。以下是一些常見的方法來設置 Node.js 應用程序的日志級別:
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'); // 錯誤級別
許多 Node.js 應用程序使用第三方日志庫,如 winston、pino 或 morgan。這些庫通常提供更靈活的日志級別設置。
winstonwinston 是一個流行的日志庫,可以通過配置來設置日志級別:
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');
pinopino 是另一個高性能的日志庫,也可以通過配置來設置日志級別:
const pino = require('pino');
const logger = pino({
level: 'info' // 設置默認日志級別
});
logger.info('This is an info message');
logger.error('This is an error message');
有些日志庫允許通過環境變量來設置日志級別。例如,winston 可以通過環境變量 WINSTON_LEVEL 來設置:
export WINSTON_LEVEL=info
node your-app.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 應用程序的日志級別。