B i M A P

Fluentd|基本概念

Fluentd Logo



Logstash v1.0 與 Logstash 的差別

Fluentd 是屬於 plugin base 的輕量化套件,只有核心具有最基本的 parsing plugin,其他需求需自行開發 plugin,腳本無法像 logstash 一樣寫 if else 的邏輯,一併要在 plugin 去實作。

Logstash 含有大量模組可以使用,腳本彈性高,也可以抽 plugin。當然輕量程度是不比 Fluentd,不過差別也並不是太大。


三大元素

source (必要),定義來源,可以多個,至少一個

filter (非必要),定義資料處理邏輯,可以多個,也可以沒有,處理排序由上至下

match (必要),定義輸出,可以多個,至少一個

  • tag (非必要):source 來源可能很多,需要透過 tag 區分要進入的 filter、match
  • filter plugin 的源碼中如果有 return 的行為,此次的 pipeling 會中止,處理下一筆資料
  • 一個元素對應一個 plugin,在 @type 中設定
<source> 
@type http
port 8888
bind 0.0.0.0
tag test.cycle
</source>
<filter test.cycle>
@type grep
<exclude>
key action
pattern ^logout$
</exclude>
</filter>
<match test.cycle>
@type stdout
</match>


Source 來源定義

可定義來源的有以下幾種:

  • in_tail
  • in_forward
  • in_udp
  • in_tcp
  • in_unix
  • in_http
  • in_syslog
  • in_exec
  • in_sample
  • in_windows_eventlog

以 in_tail 為例,因為收集 server 上的 log 的情境相當常見,參考官方文檔說明,將必要參數帶入相關參數值即可。

Parse 區塊說明:Source、Filter 可以做 Parse 區塊的設定,因為需要定義來源的解析格式,參考官方文檔時也會特別說明設定方式。

<source>
# 定義來源類型(必要)
@type tail
# 定義 log 路徑 (必要)
path /var/log/*.log
# log 的上傳紀錄檔路徑,下次不會重複上傳(必要)
pos_file /var/log/td-agent/httpd-access.log.pos
# 對來源定義 tag,讓後面的 filter、match 可以判斷是否要處理該來源的 log
tag apache.access
<parse>
# 定義 log 類型 (必要)
@type apache2
</parse>
</source>


Plugin 套件管理

基本安裝:td-agent-gem install {{ plugin_name }}

外部套件:

  • 如果是單一 rb 檔,將其置入 /etc/td-agent/plugin 中,此為預設的 plugin 存取路徑。
  • (離線適用)如果是透過 fluent-plugin-generate 產生的專案目錄,將 repo 下載後,td-agent-gem install --local /path/to/repo



Filter 資料處理

以最常使用的 grok 為使用情境,相關參數設定說明可以參考官方文檔,主要就依照自已的 parsing 需求設定就好了。

套件安裝方式:td-agent-gem install fluent-plugin-grok-parser

<filter **>
@type parser
key_name message
remove_key_name_field true
reserve_data true
<parse>
@type grok
<grok>
pattern %{GREEDYDATA:message}
</grok>
</parse>
</filter>


Match 輸出設定

以輸出到 elasticsearch 為情境

<match my.logs> 
@type elasticsearch
host localhost
port 9200
logstash_format true
</match>


完整範例設定檔

<source> 
# 定義來源類型(必要)
@type tail
# 定義 log 路徑 (必要)
path /var/log/*.log
# log 的上傳紀錄檔路徑,下次不會重複上傳(必要)
pos_file /var/log/td-agent/httpd-access.log.pos
# 對來源定義 tag,讓後面的 filter、match 可以判斷是否要處理該來源的 log
tag apache.access
<parse>
# 定義 log 類型 (必要)
@type apache2
</parse>
</source>
<filter apache.*>
@type parser
key_name message
remove_key_name_field true
reserve_data true
<parse>
@type grok
<grok>
pattern %{GREEDYDATA:message}
</grok>
</parse>
</filter>
<match **>
@type elasticsearch
host localhost
port 9200
logstash_format true
</match>


結論

Fluentd 的腳本寫法非常乾淨、一致,只要確定使用的套件,需要設定的參數,就可以快速的上手使用。但也因為是以 plugin 為基礎,在腳本的寫法上彈性並不大,大部份的工作都要有適合的 plugin 才能處理,目前也找不到太多的開源套件使用,或是已久無維護,導致適用的情境有限,或是需要多花時間編寫腳本以達成需求,因此如果是複雜度不高的 Log,使用起來會相當適合且快速。



有任何問題,或是想看新主題? 聯絡我們

延伸閱讀
winstonlu的大頭照
ELK 達人

我們致力於 ELK 的各種應用,協助企業建置相關服務。我們也提供基於 ELK 的各種解決方案,有任何問題,歡迎加入我們的官方 Line,或來信詢問,期待與您面對面的機會。