filters/mutate 插件是 Logstash 另外一個重要插件。它提供了豐富的基礎類型數據處理能力。包括類型轉換,字符串處理和字段處理等。html
類型轉換是 filters/mutate 插件最初誕生時的惟一功能。其應用場景在以前 Codec/JSON 小節已經提到。json
能夠設置的轉換類型包括:"integer","float" 和 "string"。示例以下:數組
filter { mutate { convert => ["request_time", "float"] } }
注意:mutate 除了轉換簡單的字符值,還支持對數組類型的字段進行轉換,即將 ["1","2"]
轉換成[1,2]
。但不支持對哈希類型的字段作相似處理。有這方面需求的能夠採用稍後講述的 filters/ruby 插件完成。ruby
僅對字符串類型字段有效url
gsub => ["urlparams", "[\\?#]", "_"]
filter { mutate { split => ["message", "|"] } }
隨意輸入一串以|
分割的字符,好比 "123|321|adfd|dfjld*=123",能夠看到以下輸出:spa
{ "message" => [ [0] "123", [1] "321", [2] "adfd", [3] "dfjld*=123" ], "@version" => "1", "@timestamp" => "2014-08-20T15:58:23.120Z", "host" => "raochenlindeMacBook-Air.local" }
僅對數組類型字段有效插件
咱們在以前已經用 split
割切的基礎再 join
回去。配置改爲:code
filter { mutate { split => ["message", "|"] } mutate { join => ["message", ","] } }
filter 區段以內,是順序執行的。因此咱們最後看到的輸出結果是:htm
{ "message" => "123,321,adfd,dfjld*=123", "@version" => "1", "@timestamp" => "2014-08-20T16:01:33.972Z", "host" => "raochenlindeMacBook-Air.local" }
合併兩個數組或者哈希字段。依然在以前 split 的基礎上繼續:blog
filter { mutate { split => ["message", "|"] } mutate { merge => ["message", "message"] } }
咱們會看到輸出:
{ "message" => [ [0] "123", [1] "321", [2] "adfd", [3] "dfjld*=123", [4] "123", [5] "321", [6] "adfd", [7] "dfjld*=123" ], "@version" => "1", "@timestamp" => "2014-08-20T16:05:53.711Z", "host" => "raochenlindeMacBook-Air.local" }
若是 src 字段是字符串,會自動先轉換成一個單元素的數組再合併。把上一示例中的來源字段改爲 "host":
filter { mutate { split => ["message", "|"] } mutate { merge => ["message", "host"] } }
結果變成:
{ "message" => [ [0] "123", [1] "321", [2] "adfd", [3] "dfjld*=123", [4] "raochenlindeMacBook-Air.local" ], "@version" => "1", "@timestamp" => "2014-08-20T16:07:53.533Z", "host" => [ [0] "raochenlindeMacBook-Air.local" ] }
看,目的字段 "message" 確實多了一個元素,可是來源字段 "host" 自己也由字符串類型變成數組類型了!
下面你猜,若是來源位置寫的不是字段名而是直接一個字符串,會產生什麼奇特的效果呢?
重命名某個字段,若是目的字段已經存在,會被覆蓋掉:
filter { mutate { rename => ["syslog_host", "host"] } }
更新某個字段的內容。若是字段不存在,不會新建。
做用和 update 相似,可是當字段不存在的時候,它會起到 add_field
參數同樣的效果,自動添加新的字段。
須要注意的是,filter/mutate 內部是有執行次序的。其次序以下:
rename(event) if @rename update(event) if @update replace(event) if @replace convert(event) if @convert gsub(event) if @gsub uppercase(event) if @uppercase lowercase(event) if @lowercase strip(event) if @strip remove(event) if @remove split(event) if @split join(event) if @join merge(event) if @merge filter_matched(event)
而 filter_matched
這個 filters/base.rb 裏繼承的方法也是有次序的。
@add_field.each do |field, value| end @remove_field.each do |field| end @add_tag.each do |tag| end @remove_tag.each do |tag| end