Linux 系統產生的海量日誌若無自動化分析與投遞機制,管理員極易錯過關鍵異常。本文聚焦 logwatch 這一經典日誌分析工具,講解從安裝、郵件接收者配置、報表定制到系統郵件隊列管理的完整鏈路,助你建立「日誌自動巡檢 → 郵件送達」的閉環。
/var/log/)
# CentOS/RHEL
yum install -y logwatch
# Ubuntu/Debian
apt-get install -y logwatch
編輯 /usr/share/logwatch/default.conf/logwatch.conf 或 /etc/logwatch/conf/logwatch.conf:
MailTo = admin@example.com
MailFrom = logwatch@$(hostname -f)
Detail = Med # Low/Med/High
Range = Yesterday # Today/Yesterday/All
Format = html # text/html
Encode = none
logwatch --output mail --format html --range yesterday --detail Med
mail # 進入交互模式,輸入數字查看具體郵件
mail -f /var/spool/mail/root # 直接讀取 root 郵箱文件
> /var/spool/mail/root # 截斷文件,備份先用 cp
echo "Test from $(hostname)" | mail -s "Logwatch Test" root
編輯 /etc/logwatch/conf/services/ 下對應服務文件,或建立 /etc/logwatch/conf/ignore.conf 過濾噪音:
# 忽略特定服務
Service = "-zz-network"
Service = "-zz-sys"
# 自定義過濾關鍵字(需編寫腳本放入 /etc/logwatch/scripts/services/)
logwatch 安裝後通常會在 /etc/cron.daily/0logwatch 建立每日任務。確認內容:
#!/bin/bash
/usr/sbin/logwatch --output mail
若需調整時間,可移至 /etc/cron.d/ 自定義:
# 每天 06:30 發送昨日報表
30 6 * * * root /usr/sbin/logwatch --output mail --range yesterday --detail Med
| 問題 | 原因 | 解決 |
|---|---|---|
| 收不到郵件 | MTA 未配置/防火牆/垃圾箱 | 檢查 mailq、postfix check、SPF/DKIM、郵件伺服器日誌 |
| 報表過大/過小 | Detail 級別不當 | 調整 Detail = Low/Med/High |
| 中文亂碼 | 編碼設置缺失 | 確保 Encode = none 且郵件客戶端支援 UTF-8 |
| 特定服務無報表 | 日誌格式不匹配 | 檢查 /usr/share/logwatch/scripts/services/ 對應解析腳本 |