在Debian系統中,Node.js應用程序的日志級別通常是通過應用程序本身的配置來設置的,而不是通過系統級的配置。以下是一些常見的方法來設置Node.js應用程序的日志級別:
許多Node.js日志庫(如winston
、morgan
等)支持通過環境變量來設置日志級別。
例如,使用winston
:
const winston = require('winston');
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info', // 默認日志級別為 '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' })
]
});
你可以在啟動應用程序之前設置環境變量:
LOG_LEVEL=debug node app.js
你也可以使用配置文件來設置日志級別。例如,使用config
模塊:
首先,安裝config
模塊:
npm install config
然后,創建一個配置文件config/default.json
:
{
"logging": {
"level": "debug"
}
}
在你的應用程序中使用配置:
const config = require('config');
const winston = require('winston');
const logger = winston.createLogger({
level: config.get('logging.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' })
]
});
你也可以直接在代碼中設置日志級別:
const winston = require('winston');
const logger = winston.createLogger({
level: 'debug', // 直接設置日志級別
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' })
]
});
如果你使用PM2來管理Node.js應用,可以通過PM2的配置文件來設置日志級別。
創建一個ecosystem.config.js
文件:
module.exports = {
apps: [{
name: 'my-app',
script: 'app.js',
env: {
NODE_ENV: 'development',
LOG_LEVEL: 'debug'
},
env_production: {
NODE_ENV: 'production',
LOG_LEVEL: 'info'
}
}]
};
然后使用PM2啟動應用:
pm2 start ecosystem.config.js --env production
通過這些方法,你可以在Debian系統中靈活地設置Node.js應用程序的日志級別。