在Ubuntu下,Node.js应用程序的日志级别通常是通过应用程序本身的代码来设置的。大多数Node.js应用程序使用第三方日志库,如winston、morgan或bunyan等,来处理日志记录。这些库通常允许你设置不同的日志级别,例如error、warn、info、http、verbose、debug和silly。
以下是如何在不同日志库中设置日志级别的示例:
const 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' }),
],
});
在这个例子中,我们将全局日志级别设置为info,这意味着只有info级别及以上的日志才会被记录。同时,我们将错误日志级别设置为error,这意味着只有error级别及以上的日志才会被记录到error.log文件中。
const express = require('express');
const morgan = require('morgan');
const app = express();
app.use(morgan('combined')); // 设置日志级别
在这个例子中,我们使用morgan中间件来记录HTTP请求日志。combined是预定义的日志格式之一,它包括combined、common、dev、short和tiny等选项。你可以根据需要选择合适的日志格式。
const bunyan = require('bunyan');
const logger = bunyan.createLogger({
name: 'myApp',
level: 'info', // 设置日志级别
});
在这个例子中,我们将全局日志级别设置为info,这意味着只有info级别及以上的日志才会被记录。
请注意,这些示例仅适用于特定的日志库。在你的Node.js应用程序中,你需要根据所使用的日志库来设置日志级别。