前言
有時您只想在特定條件下過濾或輸出事件。為此,您可以使用條件(conditional)。比如在elk系統中想要添加一個type類型的關鍵字來根據不同的條件賦值,最后好做統計。
條件語法
if EXPRESSION { ... } else if EXPRESSION { ... } else { ... }
比較操作
- 相等:
==
,!=
,<
,>
,<=
,>=
- 正則:
=~
(匹配正則),!~
(不匹配正則) - 包含:
in
(包含),not in
(不包含)
布爾操作
- and
(與), or
(或), nand
(非與), xor
(非或)
一元運算符
表達式可能很長且很復雜。表達式可以包含其他表達式,您可以使用!來取消表達式,並且可以使用括號(...)對它們進行分組。
- -
!
(取反) - -
()
(復合表達式) !()
(對復合表達式結果取反)
示例
如若action是login則mutate filter刪除secret字段:
filter { if [action] == "login" { mutate { remove_field => "secret" } } }
若是正則匹配,成功后添加自定義字段:
filter { if [message] =~ /\w+\s+\/\w+(\/learner\/course\/)/ { mutate { add_field => { "learner_type" => "course" } } } }
在一個條件里指定多個表達式:
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" } } }
not in示例:
output { if "_grokparsefailure" not in [tags] { elasticsearch { ... } } }
參考資料: