在Debian上设置Node.js应用程序的日志级别,通常取决于你使用的日志库或框架。以下是一些常见的Node.js日志库及其设置方法:
console.log
如果你只是使用 console.log
进行简单的日志记录,那么日志级别是由你直接在代码中设置的。例如:
console.log('This is an info message');
console.error('This is an error message');
winston
winston
是一个流行的日志库,可以通过配置来设置不同的日志级别。以下是一个简单的配置示例:
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.info('This is an info message');
logger.error('This is an error message');
pino
pino
是另一个高性能的日志库,可以通过配置来设置日志级别。以下是一个简单的配置示例:
const pino = require('pino');
const logger = pino({
level: 'info' // 设置默认日志级别
});
logger.info('This is an info message');
logger.error('This is an error message');
morgan
morgan
是一个HTTP请求日志中间件,通常用于Express应用程序。它本身没有日志级别设置,但你可以结合其他日志库来记录请求日志。例如:
const express = require('express');
const morgan = require('morgan');
const winston = require('winston');
const app = express();
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'access.log' })
]
});
app.use(morgan('combined', { stream: { write: message => logger.info(message.trim()) } }));
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
logger.info('Server is running on port 3000');
});
你也可以通过环境变量来动态设置日志级别。例如,使用 winston
:
const winston = require('winston');
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info', // 从环境变量中读取日志级别
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'combined.log' })
]
});
logger.info('This is an info message');
logger.error('This is an error message');
在Debian上运行Node.js应用程序时,可以通过设置环境变量来控制日志级别:
LOG_LEVEL=debug node app.js
通过这些方法,你可以在Debian上灵活地设置Node.js应用程序的日志级别。