萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Apache 虛擬主機訪問日誌切割配置:rotatelogs / cronolog 實現按天自動分割

背景

Apache 預設將所有訪問日誌寫入單一檔案,長期運行會導致文件過大、難以分析、佔滿磁碟。利用管道程式 rotatelogs (Apache 自帶) 或 cronolog (第三方) 可實現**按天/按大小自動切割**,無需重啟服務。

方案一:rotatelogs (Apache 內建,無額外依賴)

Linux 系統

ErrorLog "|/usr/local/apache/bin/rotatelogs /home/logs/www/%Y_%m_%d_error_log 86400 480"
CustomLog "|/usr/local/apache/bin/rotatelogs /home/logs/www/%Y_%m_%d_access_log 86400 480" common
  • 86400:切割間隔秒數 (24h)。
  • 480:UTC 偏移分鐘 (中國時區 UTC+8 = 480),確保按「本地零點」切割。
  • 日誌格式 common = %h %l %u %t "%r" %>s %b。

Windows 系統

ErrorLog "|bin/rotatelogs.exe logs/site1/error-%y%m%d.log 86400 480"
CustomLog "|bin/rotatelogs.exe logs/site1/access-%y%m%d.log 86400 480" common

路徑相對於 Apache 安裝目錄,建議使用絕對路徑。

方案二:cronolog (功能更豐富,支援自定義格式、多日誌流)

安裝

wget https://freshmeat.net/redir/cronolog/.../cronolog-1.6.2.tar.gz
tar zxf cronolog-1.6.2.tar.gz && cd cronolog-1.6.2
./configure --prefix=/usr/local/cronolog && make && make install

httpd.conf 完整範例

# 錯誤日誌
ErrorLog "|/usr/local/cronolog/sbin/cronolog /usr/local/apache-2.2.15/logs/error_log_%Y%m%d"
LogLevel warn

<IfModule log_config_module>
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common
    <IfModule logio_module>
        LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    # 訪問日誌按天切割
    CustomLog "|/usr/local/cronolog/sbin/cronolog /usr/local/apache-2.2.15/logs/access_log_%Y%m%d" combined
    # Referer 獨立日誌
    CustomLog "|/usr/local/cronolog/sbin/cronolog /usr/local/apache-2.2.15/logs/referer_log" Referer
    # User-Agent 獨立日誌
    CustomLog "|/usr/local/cronolog/sbin/cronolog /usr/local/apache-2.2.15/logs/agent_log" Agent
</IfModule>

虛擬主機獨立日誌配置範例

<VirtualHost 192.168.1.3:588>
    DocumentRoot "E:/www/"
    ServerName 192.168.1.3

    # 僅記錄訪問日誌,按天切割
    CustomLog "|bin/rotatelogs.exe logs/vicp_net_access-%y%m%d.log 86400 480" common

    # Rewrite 規則示例
    RewriteEngine On
    RewriteRule /wp-([0-9]+)(.?)$ /plus/list.php?tid=$1
    RewriteRule /wp-([0-9]+)-([0-9]+)-([0-9]+)(.?)$ /plus/list.php?tid=$1&totalresult=$2&ageNo=$3
    RewriteRule /([0-9]+)(.?)$ /plus/view.php?arcID=$1
</VirtualHost>

日誌分析與維護建議

  • 定期清理: 配合 find /log/path -mtime +30 -name "*.log" -delete 保留 30 天。
  • 日誌分析: GoAccess、AWStats、ELK Stack (Filebeat→Logstash→Elasticsearch→Kibana)。
  • 權限: 日誌目錄屬主 www:www,權限 750,防止洩露敏感信息。
  • 管道程式掛掉風險: Apache 2.4+ 支援 CustomLog "||/usr/local/sbin/rotatelogs ..." (雙管道) 實現優雅降級。

rotatelogs vs cronolog 選型

特性rotatelogscronolog
依賴Apache 內建需額外編譯安裝
切割精度秒級間隔支援 strftime 任意格式
多日誌流單管道單流單進程可分流多虛擬主機
Windows 支援有 (.exe)需 Cygwin/MinGW 編譯
性能極低開銷略高但可忽略

簡單場景用 rotatelogs;多虛擬主機、複雜命名規則、需單進程管理多流時選 cronolog。

copyright © 萬盛學電腦網 all rights reserved