Logwatch 是一套基於 Perl 的日誌分析報表工具,能將分散在 /var/log 的系統與服務日誌彙整為人類可讀的摘要,支援郵件寄送、檔案儲存、螢幕輸出,並可透過 cron 定期執行。本文涵蓋安裝、核心配置、報告範圍控制、服務擴充與常見坑點。
| 發行版 | 指令 |
|---|---|
| Debian/Ubuntu | sudo apt update && sudo apt install logwatch |
| CentOS/RHEL/Fedora | sudo dnf install logwatch / sudo yum install logwatch |
| openSUSE | sudo zypper install logwatch |
| Arch Linux | sudo pacman -S logwatch |
/etc/logwatch/conf/logwatch.conf安裝後預設為空,會繼承 /usr/share/logwatch/default.conf/logwatch.conf 的系統預設值。常用參數:
| 參數 | 說明 | 範例值 |
|---|---|---|
Detail | 報告詳細度 | High / Med / Low / 10 |
MailTo | 收件者信箱(多筆用空白分隔) | admin@example.com backup@example.com |
Range | 報告時間範圍 | Yesterday / Today / All / "-5 days" |
Service | 指定分析服務(多行可疊加) | sshd / http / All |
Format | 輸出格式 | text / html |
Output | 輸出目標 | mail / file / stdout |
Filename | 輸出檔案路徑(Output=file 時) | /var/log/logwatch/report.log |
Encode | 編碼 | utf-8 |
Range 進階用法Range = "between -7 days and -3 days"
Range = "since September 15, 2024"
Range = "first Friday in October"
Range = "2024/10/15 12:50:15 for that second"
使用自由格式需安裝 Perl Date::Manip 模組:
sudo cpanm Date::Manip
/usr/share/logwatch/scripts/services/ 建立 myservice(Perl 腳本)。ProcessLogs() 子程式,解析日誌並輸出報告片段。sshd、http)撰寫。logwatch.conf 加入 Service = myservice。# /etc/cron.daily/00logwatch (Debian/Ubuntu 預設已建立)
# 手動建立每日 06:00 執行並寄送郵件
0 6 * * * root /usr/sbin/logwatch --output mail --mailto admin@example.com --detail High --range Yesterday
本機需安裝並設定 MTA(Postfix / Sendmail / Exim),且能正常投遞外部郵件。測試:
echo "test" | mail -s "logwatch test" admin@example.com
logrotate 保持單檔適中大小。| 現象 | 檢查方向 |
|---|---|
| 郵件未收到 | MTA 設定、垃圾信箱、MailTo 拼字、Output = mail |
| 報告為空 | Range 設定、日誌檔案權限、服務腳本路徑 |
| 中文亂碼 | 確認 Encode = utf-8、日誌檔案實際編碼 |
Logwatch 以「零代理、純 Perl、高擴充性」著稱,適合中小型環境的日誌歸檔與異常偵測輔助;大規模環境建議搭配 ELK/EFK 或 Loki/Grafana 堆疊。