Ubuntu系統配置Filebeat定時任務的常用方法
Cron是Ubuntu系統自帶的定時任務管理工具,適合需要定期運行Filebeat采集任務的場景(如每分鐘、每小時采集一次日志)。
crontab -e(若需要root權限,用sudo crontab -e),進入編輯模式。/var/log/*.log文件并發送到Elasticsearch):0 1 * * * /usr/share/filebeat/filebeat -e -c /etc/filebeat/filebeat.yml* * * * * /usr/share/filebeat/filebeat -e -c /etc/filebeat/filebeat.yml/usr/share/filebeat/filebeat是Filebeat的可執行文件路徑(可通過which filebeat命令確認);-e參數將錯誤日志輸出到stderr;-c指定配置文件路徑。Ctrl+X→Y→Enter),通過crontab -l(當前用戶)或sudo crontab -l(root用戶)查看已添加的任務。Systemd定時器是Ubuntu 16.04及以上版本推薦的方式,支持秒級精度和依賴管理,適合需要與系統服務深度集成的場景。
/etc/systemd/system/filebeat.service,內容如下:[Unit]
Description=Filebeat Log Shipper
After=network.target
[Service]
Type=simple
User=filebeat
Group=filebeat
ExecStart=/usr/share/filebeat/filebeat -e -c /etc/filebeat/filebeat.yml
Restart=on-failure
[Install]
WantedBy=multi-user.target
注:User和Group設置為filebeat(默認用戶),避免權限問題;Restart=on-failure確保服務異常時自動重啟。/etc/systemd/system/filebeat.timer,內容如下(以“每天凌晨1點執行”為例):[Unit]
Description=Run Filebeat daily at 1:00 AM
[Timer]
OnCalendar=*-*-* 01:00:00
Persistent=true
[Install]
WantedBy=timers.target
注:OnCalendar支持多種時間格式(如*-*-* 01:00:00表示每天凌晨1點,*/5 * * * *表示每5分鐘);Persistent=true表示若系統關機錯過執行時間,會在下次啟動后補執行。sudo systemctl daemon-reload # 重新加載Systemd配置
sudo systemctl enable --now filebeat.timer # 啟用并立即啟動定時器
systemctl list-timers | grep filebeat # 查看filebeat.timer的狀態
journalctl -u filebeat -f # 查看filebeat服務的日志
若需調整Filebeat采集日志的頻率(而非執行任務的頻率),可直接修改filebeat.yml配置文件:
sudo nano /etc/filebeat/filebeat.yml。scan_frequency參數:在filebeat.inputs部分添加scan_frequency(單位:秒),例如每30秒掃描一次日志文件:filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/*.log
scan_frequency: 30s # 調整采集間隔
sudo systemctl restart filebeat。