logwatch 是一套日誌分析工具,能將系統日誌整理成易讀的摘要報告。本文說明安裝、設定與實際使用方式。
logwatch 的定位是「產生摘要」,並非即時監控。因此它通常由 cron 定時調度,或在需要時手動執行。報告可寄送到信箱、存成檔案,或直接印在螢幕上。報告的詳細程度與涵蓋範圍完全可自訂,處理引擎也可擴充——想讓新應用的日誌被納入,只要用 Perl 寫一支處理腳本掛上去即可。唯一的小缺點是報告中沒有精確時間戳,需要精確時間時仍得回頭查原始日誌。
# aptitude install logwatch # Debian 系列 # yum install logwatch # Red Hat 系列
主要設定檔為 /etc/logwatch/conf/logwatch.conf,預設是空的,其中的選項會覆蓋 /usr/share/logwatch/default.conf/logwatch.conf 的系統預設值。若執行時帶入參數,參數會再覆蓋設定檔。
Detail = High # 詳細程度,可為 Low/Med/High 或數字 0/5/10 MailTo = youremailaddress@yourdomain.com Range = Today # Yesterday / Today / All Service = http Format = html # text 或 html Output = mail # file / mail / stdout
Range 也支援自由寫法,例如 "2 hours ago for that hour"、"-5 days"、"between -7 days and -3 days"、"since September 15, 2014"、"first Friday in October",但這類寫法需要另外從 CPAN 安裝 Perl 的 Date::Manip 模組。若 Range 設為 All,還要加上 Archive = yes,才會一併處理已歸檔的日誌。
Service 指定要監控的服務,/usr/share/logwatch/scripts/services 底下已內建 pam、secure、iptables、syslogd、sudo、sshd、http、fail2ban、samba 等。若要指定特定服務,記得把預設設定檔中的 Service = All 那行註解掉。MailTo 要能運作,主機上必須先有 sendmail、Postfix 這類本地 MTA。
Detail=High MailTo= youremailaddress@yourdomain.com Range=Today Service= http Service= postfix Service= zz-disk_space Format= html Output= mail
等價的指令寫法:
# logwatch --detail 10 --mailto youremailaddress@yourdomain.com --range today \ --service http --service postfix --service zz-disk_space --format html --output mail
報告郵件頂端會有跳轉連結,各服務段落末尾也有「返回頂部」。
Detail=High Range=Today Service= http Service= postfix Service= zz-disk_space Format= html Output= file Filename=/var/www/html/logs/dev1.html
# crontab -e 15 12 * * 1,2,3,4,5 /sbin/logwatch
以上設定會在每個工作日中午 12:15 執行一次 logwatch。