在Ubuntu系统中,Node.js应用程序的日志级别通常是通过应用程序代码或配置文件来设置的。以下是一些常见的方法来设置Node.js应用程序的日志级别:
如果你使用的是像winston
、morgan
或其他日志库,你可以在代码中直接设置日志级别。
winston
const winston = require('winston');
const logger = winston.createLogger({
level: 'info', // 设置日志级别为info
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
morgan
const express = require('express');
const morgan = require('morgan');
const app = express();
app.use(morgan('combined')); // 默认日志级别是combined
// 或者你可以设置特定的日志级别
app.use(morgan('tiny')); // 日志级别为tiny
许多Node.js应用程序允许通过环境变量来配置日志级别。
winston
const winston = require('winston');
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info', // 从环境变量中读取日志级别,默认为info
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
你可以在启动应用程序时设置环境变量:
LOG_LEVEL=debug node app.js
如果你使用的是像config
模块或其他配置管理工具,你可以在配置文件中设置日志级别。
config
模块const config = require('config');
const logger = winston.createLogger({
level: config.get('logging.level') || 'info', // 从配置文件中读取日志级别,默认为info
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
在config/default.json
中设置日志级别:
{
"logging": {
"level": "info"
}
}
选择哪种方法取决于你的具体需求和应用程序的架构。通常,通过代码或环境变量设置日志级别是最常见和灵活的方法。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: 在ubuntu中使用splint时需要注意什么