溫馨提示×

如何在Ubuntu上清理Node.js日志

小樊
37
2025-06-08 14:40:38
欄目: 編程語言

在 Ubuntu 上清理 Node.js 應用程序的日志文件,可以通過以下幾種方法實現:

方法一:手動刪除日志文件

  1. 找到日志文件的位置

    • 通常情況下,Node.js 應用程序的日志文件會保存在應用程序的工作目錄下,或者配置文件中指定的日志目錄中。
    • 常見的日志文件名包括 app.log、access.log 等。
  2. 刪除日志文件

    • 打開終端并導航到日志文件所在的目錄。
    • 使用 rm 命令刪除日志文件。例如:
      cd /path/to/logs
      rm app.log
      

方法二:使用日志輪轉工具

日志輪轉工具可以幫助你自動管理日志文件的大小和數量,防止日志文件過大。

  1. 安裝 logrotate

    sudo apt-get update
    sudo apt-get install logrotate
    
  2. 配置 logrotate

    • 創建一個新的 logrotate 配置文件,例如 /etc/logrotate.d/nodejs。
    • 編輯該文件,添加以下內容:
      /path/to/logs/*.log {
          daily
          missingok
          rotate 7
          compress
          notifempty
          create 0640 root adm
      }
      
    • 解釋:
      • daily:每天輪轉一次日志。
      • missingok:如果日志文件不存在,不會報錯。
      • rotate 7:保留最近 7 天的日志文件。
      • compress:壓縮舊的日志文件。
      • notifempty:如果日志文件為空,不進行輪轉。
      • create 0640 root adm:創建新的日志文件,權限為 0640,屬主為 root,屬組為 adm。
  3. 測試配置

    sudo logrotate -f /etc/logrotate.d/nodejs
    

方法三:使用 Node.js 日志庫

如果你使用的是 Node.js 的日志庫(如 winston、morgan 等),可以在代碼中配置日志輪轉。

  1. 安裝 winstonwinston-daily-rotate-file

    npm install winston winston-daily-rotate-file
    
  2. 配置 winston

    const winston = require('winston');
    const { DailyRotateFile } = require('winston-daily-rotate-file');
    
    const transport = new DailyRotateFile({
      filename: 'application-%DATE%.log',
      datePattern: 'YYYY-MM-DD-HH',
      zippedArchive: true,
      maxSize: '20m',
      maxFiles: '14d'
    });
    
    const logger = winston.createLogger({
      level: 'info',
      format: winston.format.json(),
      transports: [
        transport
      ]
    });
    
    logger.info('Hello, world!');
    

通過以上方法,你可以有效地管理和清理 Ubuntu 上 Node.js 應用程序的日志文件。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女