Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

CentOS Linux 使用 logrotate 實現日誌分割與管理

編輯:Linux 教學

logrotate 是一款強大的日誌文件管理工具,能自動分割、壓縮、刪除舊日誌並創建新日誌,有效節省磁盤空間。本文詳細介紹其在 CentOS 系統上的配置與使用方法。

基本命令語法

logrotate [OPTION...] <configfile>

常用選項:

  • -d, --debug:除錯模式,測試配置文件語法
  • -f, --force:強制執行日誌輪轉
  • -m, --mail=command:將日誌發送至指定郵箱
  • -s, --state=statefile:指定狀態文件路徑
  • -v, --verbose:顯示詳細執行過程

主配置文件解析

預設配置文件位於 /etc/logrotate.conf,核心參數說明:

  • weekly:每週輪轉一次
  • rotate 4:保留 4 個備份文件
  • create:輪轉後自動創建新日誌文件
  • compress:啟用壓縮(預設註釋)
  • include /etc/logrotate.d:引入自定義配置目錄

Nginx 日誌管理實戰

針對 LNMP 一鍵安裝包中的 Nginx 訪問日誌(位於 /home/wwwlogs),創建專用配置:

vim /etc/logrotate.d/nginx

配置內容:

/home/wwwlogs/access.log /home/wwwlogs/nginx_error.log {
    notifempty
    daily
    rotate 5
    sharedscripts
    postrotate
        /bin/kill -HUP `/bin/cat /usr/local/nginx/logs/nginx.pid`
    endscript
}

關鍵指令解析:

  • notifempty:空文件不輪轉
  • daily:每日輪轉
  • rotate 5:保留 5 份備份
  • postrotate/endscript:輪轉後執行腳本,發送 HUP 信號讓 Nginx 重新打開日誌文件

執行與自動化

手動測試:

/usr/sbin/logrotate -vf /etc/logrotate.conf

自動執行機制:系統預置 /etc/cron.daily/logrotate 腳本,由 cron 每日自動調用,無需額外配置。

Copyright © Windows教程網 All Rights Reserved