在Ubuntu系统中,Node.js应用程序的日志级别通常是通过应用程序本身的配置来设置的。大多数Node.js应用程序使用第三方日志库,如winston
、bunyan
或morgan
等,来处理日志记录。这些库通常允许你设置不同的日志级别。
以下是一些常见的Node.js日志库及其日志级别的设置方法:
Winston是一个流行的日志库,支持多种传输和格式化选项。你可以通过设置level
属性来调整日志级别。
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'; // 可以设置为 'silly', 'verbose', 'debug', 'info', 'warn', 'error', 'fatal'
Bunyan是另一个流行的日志库,也支持日志级别的设置。
const bunyan = require('bunyan');
const logger = bunyan.createLogger({
name: 'myApp',
streams: [
{
level: 'info', // 默认日志级别
stream: process.stdout
},
{
level: 'error', // 错误日志级别
path: 'error.log'
}
]
});
// 设置日志级别
logger.level = 'debug'; // 可以设置为 'trace', 'debug', 'info', 'warn', 'error'
Morgan是一个HTTP请求日志中间件,通常用于Express应用程序。
const express = require('express');
const morgan = require('morgan');
const app = express();
// 默认日志级别是 'combined'
app.use(morgan('combined'));
// 设置日志级别
app.use(morgan('dev')); // 可以设置为 'tiny', 'short', 'combined', 'common', 'dev'
有些应用程序允许通过环境变量来设置日志级别。例如,使用winston
时,你可以这样做:
export WINSTON_LEVEL=debug
node app.js
然后在代码中读取这个环境变量:
const winston = require('winston');
const logger = winston.createLogger({
level: process.env.WINSTON_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' })
]
});
通过这些方法,你可以在Ubuntu系统中灵活地设置Node.js应用程序的日志级别。