條件判斷(只適用於filter和output)
logstash在處理數據(配置文件中)時,支持通過判斷條件(if,else if,else
)語句進行編寫
語法格式:
if EXPRESSION {
...
} else if EXPRESSION {
...
} else {
...
}
**`EXPRESSION`:** - 比較運算符(只支持小寫): * `==`,`!=`,`<`,`>`,`<=`,`>=` * `=~(匹配正則)`,`!~(不匹配正則)` * `in(包含)`,`not in(不包含)` - 布爾運算符: * `and(與)`,`or(或)`,`nand(非與)`,`xor(非或)` - 一元運算符: * `!(取反)` * `()(復合表達式)`,`!()(對復合表達式取反)`
在比較運算中,字段用[]
,字符用""
,數組[array_name][index_name]
當action字段為"login"時,刪除secret字段 ``` filter { if [action] == "login" { mutate { remove_field => "secret" } } if [fields][log_name] == "nginx1" { #array數組寫法 ... } } ```
一個條件指定多個表達式 ``` output { # Send production errors to pagerduty if [loglevel] == "ERROR" and [deployment] == "production" { pagerduty { ... } } } ```
`in`操作符判斷字段是否包含 ``` filter { if [foo] in [foobar] { mutate { add_tag => "field in field" } } if [foo] in "foo" { mutate { add_tag => "field in string" } } if "hello" in [greeting] { mutate { add_tag => "string in field" } } if [foo] in ["hello", "world", "foo"] { mutate { add_tag => "field in list" } } if [missing] in [alsomissing] { mutate { add_tag => "shouldnotexist" } } if !("foo" in ["hello", "world"]) { mutate { add_tag => "shouldexist" } } } output { if "_grokparsefailure" not in [tags] { elasticsearch { ... } } } ```
sprintf輸出
匹配到的字段輸出都可使用%{}
括起來引用
output {
statsd {
increment => "apache.%{[response][status]}"
}
}
#也可以格式化時間,但是這里的yyyy時間定義是這台logstash的時間,而不是filter插件中date模塊分析的日期,如果需要以日志的時間,則需要將日志時間拆分后存儲成另外的字段,后在output中引用。
output {
file {
path => "/var/log/%{type}.%{+yyyy.MM.dd.HH}"
}
}