阅读量:3
在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"
}
}
总结
选择哪种方法取决于你的具体需求和应用程序的架构。通常,通过代码或环境变量设置日志级别是最常见和灵活的方法。
以上就是关于“Ubuntu中Node.js日志级别怎么设”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm