在Ubuntu上设置Node.js应用程序的日志级别通常涉及修改应用程序的代码或配置文件,或者调整日志库的设置。以下是一些常见的方法:
如果你使用的是像winston或morgan这样的日志库,你可以在代码中直接设置日志级别。
winstonconst winston = require('winston');
const logger = winston.createLogger({
level: 'info', // 设置日志级别
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
morganconst morgan = require('morgan');
const express = require('express');
const app = express();
app.use(morgan('combined')); // 默认日志级别是 'combined'
许多日志库支持通过环境变量来设置日志级别。
winstonconst winston = require('winston');
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info', // 从环境变量读取日志级别
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
你可以在启动应用程序之前设置环境变量:
export LOG_LEVEL=debug
node app.js
morganconst morgan = require('morgan');
const express = require('express');
const app = express();
app.use(morgan(process.env.LOG_LEVEL || 'combined')); // 从环境变量读取日志级别
同样,你可以在启动应用程序之前设置环境变量:
export LOG_LEVEL=combined
node app.js
如果你使用的是配置文件来管理应用程序的设置,你可以在配置文件中设置日志级别。
config库假设你有一个config目录,其中包含不同环境的配置文件(如default.json, development.json, production.json)。
// config/development.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.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 start ecosystem.config.js --env development
通过这些方法,你可以在Ubuntu上灵活地设置Node.js应用程序的日志级别。选择哪种方法取决于你的具体需求和项目结构。