如何在Ubuntu上配置Node.js日志

355
2025/4/13 3:32:23
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Ubuntu上配置Node.js应用程序的日志记录可以通过多种方式实现,以下是一些常见的方法:

1. 使用内置的console.log

最简单的方法是使用Node.js内置的console.log方法来记录日志。这种方法适用于开发和调试阶段。

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  console.log('Hello World!');
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

2. 使用日志库

为了更好地管理和分析日志,可以使用一些流行的日志库,如winstonmorgan

使用winston

winston是一个功能强大的日志库,支持多种传输方式(控制台、文件、HTTP等)。

  1. 安装winston

    npm install winston
    
  2. 配置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' })
      ]
    });
    
    if (process.env.NODE_ENV !== 'production') {
      logger.add(new winston.transports.Console({
        format: winston.format.simple()
      }));
    }
    
    app.get('/', (req, res) => {
      logger.info('Hello World!');
      res.send('Hello World!');
    });
    
    app.listen(port, () => {
      logger.info(`Server running at http://localhost:${port}/`);
    });
    

使用morgan

morgan是一个HTTP请求日志中间件,适用于Express应用程序。

  1. 安装morgan

    npm install morgan
    
  2. 配置morgan

    const morgan = require('morgan');
    const fs = require('fs');
    const path = require('path');
    
    const accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' });
    
    app.use(morgan('combined', { stream: accessLogStream }));
    
    app.get('/', (req, res) => {
      res.send('Hello World!');
    });
    
    app.listen(port, () => {
      console.log(`Server running at http://localhost:${port}/`);
    });
    

3. 使用环境变量配置日志级别

可以通过环境变量来动态配置日志级别,这样可以在不同的环境中使用不同的日志级别。

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: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

app.get('/', (req, res) => {
  logger.info('Hello World!');
  res.send('Hello World!');
});

app.listen(port, () => {
  logger.info(`Server running at http://localhost:${port}/`);
});

在启动应用程序时,可以通过设置环境变量来配置日志级别:

LOG_LEVEL=debug node app.js

4. 使用日志轮转

为了防止日志文件过大,可以使用日志轮转工具,如logrotate

  1. 安装logrotate

    sudo apt-get install logrotate
    
  2. 创建一个logrotate配置文件:

    sudo nano /etc/logrotate.d/nodejs
    
  3. 添加以下内容:

    /path/to/your/nodejs/logs/*.log {
      daily
      missingok
      rotate 7
      compress
      notifempty
      create 0640 root adm
    }
    
  4. 确保你的Node.js应用程序将日志写入指定的目录。

通过以上方法,你可以在Ubuntu上灵活地配置和管理Node.js应用程序的日志。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: 如何解决Node.js日志冲突