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

Squid 日志文件過大處理方案:logrotate 配置與自動輪轉

編輯:Linux 教學

問題現象

Squid 運行久了,/var/log/squid/access.log、cache.log、store.log 體積暴增,佔滿磁盤、影響性能。需配置自動輪轉、壓縮、保留策略。

方案一:系統 logrotate(推薦,通用)

1. 編輯 /etc/logrotate.d/squid

/var/log/squid/access.log {
    daily                    # 每天輪轉
    rotate 30                # 保留 30 個舊文件
    compress                 # gzip 壓縮
    delaycompress            # 上一輪不壓縮,便於即時分析
    missingok                # 文件不存在不報錯
    notifempty               # 空文件不輪轉
    create 640 squid squid   # 新建文件權限、用戶組
    sharedscripts            # 多文件共用 postrotate 腳本
    postrotate
        /usr/sbin/squid -k rotate > /dev/null 2>&1 || true
    endscript
}

/var/log/squid/cache.log {
    weekly
    rotate 8
    compress
    delaycompress
    missingok
    notifempty
    create 640 squid squid
    sharedscripts
    postrotate
        /usr/sbin/squid -k rotate > /dev/null 2>&1 || true
    endscript
}

/var/log/squid/store.log {
    weekly
    rotate 4
    compress
    delaycompress
    missingok
    notifempty
    create 640 squid squid
    sharedscripts
    postrotate
        /usr/sbin/squid -k rotate > /dev/null 2>&1 || true
    endscript
}

2. 關鍵參數解讀

  • daily/weekly/monthly:輪轉頻率。
  • rotate N:保留 N 個歸檔。
  • compress:啟用 gzip,節省空間。
  • delaycompress:最新歸檔不壓縮,下次輪轉時壓縮,方便 tail -f 實時看日志。
  • postrotate ... endscript:輪轉後發送 squid -k rotate 信號,讓 Squid 重新打開日志文件(關鍵,否則 Squid 繼續寫舊 fd,新文件無內容)。
  • sharedscripts:多文件匹配時只執行一次 postrotate。

3. 測試配置

logrotate -d /etc/logrotate.d/squid   # debug 模式,不實際執行
logrotate -f /etc/logrotate.d/squid   # 強制執行一次

方案二:Squid 內建 logfile_rotate + crontab(舊版常用)

1. 修改 squid.conf

logfile_rotate 10   # 保留 10 個輪轉文件(配合 squid -k rotate)

2. 添加定時任務

# /etc/crontab 或 crontab -e -u squid
0 0 * * * squid /usr/sbin/squid -k rotate   # 每天 00:00 輪轉

3. 生效

crontab /etc/crontab   # 若編輯 /etc/crontab
# 或 systemctl reload cron

缺點:不支持壓縮、無 delaycompress、權限管理弱,建議遷移至 logrotate。

方案三:systemd 臨時文件 + journalctl(現代系統)

若 Squid 以 systemd 服務運行且配置 StandardOutput=journal、StandardError=journal,日志進入 journald,由 SystemMaxUse 限制總大小,無需額外輪轉。但傳統文件日志仍推薦 logrotate。

常見坑與排查

現象原因解決
輪轉後新文件無內容未發送 squid -k rotate 或信號發送失敗檢查 postrotate 腳本路徑、權限、Squid 進程是否存活
舊日志未壓縮缺少 compress 或 delaycompress 邏輯誤解確認配置,delaycompress 導致最新歸檔下次才壓縮
權限報錯create 指定的用戶組不存在確認 squid 用戶組存在,或改為 root adm
磁盤仍滿rotate 數量過大或頻率過低調整 rotate、改 daily、啟用 compress

最佳實踐建議

  1. 統一使用 logrotate,配置放入 /etc/logrotate.d/squid,由系統每日 /etc/cron.daily/logrotate 自動執行。
  2. access.log 設 daily rotate 30,cache.log 設 weekly rotate 8,store.log 視磁盤決定(建議關閉 store_log 節省 IO)。
  3. 啟用 compress + delaycompress 平衡空間與實時分析。
  4. 定期 logrotate -d 檢查配置正確性。
  5. 關鍵日志(審計、計費)另行同步至集中日志平台(ELK/Loki/Kafka),本地僅保留短期。

結語

Squid 日志增長迅速,配置 logrotate + squid -k rotate 信號重開文件是標準解法。合理設置輪轉頻率、保留份數、壓縮策略,配合監控告警,即可徹底解決日志佔滿磁盤問題。

Copyright © Windows教程網 All Rights Reserved