在CentOS系统中,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' })
]
});
// 设置日志级别
process.env.LOG_LEVEL = 'debug'; // 可以在运行时更改日志级别
你也可以通过配置文件来设置日志级别。
config
模块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' })
]
});
配置文件config/default.json
:
{
"logging": {
"level": "info"
}
}
你也可以在代码中直接设置日志级别。
winston
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.level = 'debug';
如果你使用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
通过这些方法,你可以在CentOS系统中灵活地设置Node.js应用程序的日志级别。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: centos dhcpclient如何配置