Home ELK Filebeat With Log Rotate
Post
Cancel

ELK Filebeat With Log Rotate

Log Rotate意思是當log隨著時間擴大後,能夠自動打包壓縮或是清除掉舊log,以免系統空間被log吃光。

ELK Filebeat並無支援log rotate的功能,Beats主要功能是做log shipping,不包含log rotate,因此需要透過額外的方式做。

在此文章中測試環境為 Ubuntu Server 18.04 LTS

方法1: logrotate Tool

網路上查到大部分幾乎都是採用Linux內建的logrotate工具來配合Filebeat,一般Linux系統的套件如syslog, apt-get等等其實都已經有使用logrotate這個工具來做管理,這個工具可以設定定期或是根據大小來做rotate

以下為一個小範例:

  1. /var/log底下建立一個pohsien.log。 ```bash $ cd /var/log; vim pohsien.log $ ls -l pohsien.log

-rw-r–r– 1 root root 204 Aug 20 09:47 pohsien.log ```

  1. /var/log/pohsien.log加到logrotate設定檔裡面。
    1
    
     $ vim /etc/logrotate.conf
    

    新增以下內容

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
     /var/log/pohsien.log{
         # 大小超過500KB就執行log rotate
         maxsize 500K
         # 將舊的檔案壓縮,並創建新的pohsien.log檔
         # 如果沒壓縮的話,舊檔會改名,然後一樣會創建新的pohsien.log檔
         compress
         # 做超過兩次log rotate就把最舊的資料砍掉,也就是最多只會留兩個壓縮檔
         rotate 2
     }
    
  2. 測試log rotate 重複寫入pohsien.log然後手動執行logrotate,可以發現當檔案超過500KB,就會自動產生pohsien.log.x.gz,且最多只會有兩個壓縮檔,最舊的會一直被砍掉。

    手動執行logrotate

    1
    
     $ logrotate -v /etc/logrotate.conf
    
  3. 查看結果
    1
    
     $ ls -l /var/log 
    

注意事項

在此範例中只有使用到一些功能,實際上logrotate可用的功能相當多,可視各種情境做調整。

另外logrotate是使用cronjob執行的,在Ubuntu預設是15分鐘執行一次,如果想要自訂執行時間可以自己另外寫cronjob執行logrotate,另外要注意的是如果要跟filebeat一起使用,需要配合好兩個的執行時間。

參考資料

  1. 鳥哥的Linux私房菜 Logrotate - http://linux.vbird.org/linux_basic/0570syslog.php#rotate
  2. How to Use logrotate to Manage Log Files - https://www.linode.com/docs/uptime/logs/use-logrotate-to-manage-log-files/

相關討論

  1. Log rotation and filebeat - https://discuss.elastic.co/t/log-rotation-and-filebeat/140285

方法2: 檢查filebeat registry

Elasticsearch staff在討論區 文章1文章2有提到一個比較tricky的方式:

  1. filebeat每次成功傳送完檔案後會把記錄寫在/var/lib/filebeat/registry/filebeat/data.json
  2. 寫一隻cronjob或是其他程式檢查data.json裡的offset是否跟log檔案大小一樣,如果一樣就代表傳輸完了,然後刪掉傳輸完的log檔案。

相關討論

  1. Delete processed log entries - https://discuss.elastic.co/t/delete-processed-log-entries/75960
  2. FileBeats -Are there any ways we can delete the log files after file beat harvest the data to logstash - https://discuss.elastic.co/t/filebeats-are-there-any-ways-we-can-delete-the-log-files-after-file-beat-harvest-the-data-to-logstash/177997

文章內容的轉載、重製、發佈,請註明出處: https://blog.phshih.com/

This post is licensed under CC BY 4.0 by the author.

iThome Kubernetes Summit 2019 心得

End-to-End Testing for Kubernetes (Part I) - kubetest