debian

Debian上Node.js日志级别怎么设置

小樊
35
2025-04-03 11:33:08
栏目: 编程语言

在Debian上设置Node.js应用程序的日志级别,通常取决于你使用的日志库或框架。以下是一些常见的Node.js日志库及其设置方法:

1. 使用 console.log

如果你只是使用 console.log 进行简单的日志记录,那么日志级别是由你直接在代码中设置的。例如:

console.log('This is an info message');
console.error('This is an error message');

2. 使用 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');

3. 使用 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');

4. 使用 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');
});

5. 使用环境变量

你也可以通过环境变量来动态设置日志级别。例如,使用 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应用程序的日志级别。

0
看了该问题的人还看了