1. 程式人生 > >logstash的conditional語句(if語句出錯)

logstash的conditional語句(if語句出錯)

語句的基本形式:
條件判斷

使用條件來決定filter和output處理特定的事件。logstash條件類似於程式語言。條件支援if、else if、else語句,可以巢狀。
條件語法如下:

if EXPRESSION {
  ...
} else if EXPRESSION {
  ...
} else {
  ...
}

比較操作有:
相等: ==, !=, <, >, <=, >=
正則: =~(匹配正則), !~(不匹配正則)
包含: in(包含), not in(不包含)
布林操作:
and(與), or(或), nand(非與), xor(非或)
一元運算子:
!(取反)
()(複合表示式), !()(對複合表示式結果取反)
語句的具體用法請參照參考url

使用中遇到的問題:
1、if[foo] in "String"在執行這樣的語句是,報錯如下:

Exception in pipelineworker, the pipeline stopped processing new events, please check your filter configuration and restart Logstash. {"exception"=>#<TypeError: can't convert nil into String>, "backtrace"=>["org/jruby/RubyString.java:4462:in `include?'
", "(eval):97:in `initialize'", "org/jruby/RubyArray.java:1613:in `each'", "(eval):95:in `initialize'", "org/jruby/RubyProc.java:281:in `call'", "(eval):68:in `filter_func'", "/opt/logstash-2.3.4/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/pipeline.rb:267:in `filter_batch'", "org/jruby/RubyArray.java:1613:in `each'
", "org/jruby/RubyEnumerable.java:852:in `inject'", "/opt/logstash-2.3.4/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/pipeline.rb:265:in `filter_batch'", "/opt/logstash-2.3.4/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/pipeline.rb:223:in `worker_loop'", "/opt/logstash-2.3.4/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/pipeline.rb:201:in `start_workers'"], :level=>:error} TypeError: can't convert nil into String include? at org/jruby/RubyString.java:4462 initialize at (eval):97 each at org/jruby/RubyArray.java:1613 initialize at (eval):95 call at org/jruby/RubyProc.java:281 filter_func at (eval):68 filter_batch at /opt/logstash-2.3.4/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/pipeline.rb:267 each at org/jruby/RubyArray.java:1613 inject at org/jruby/RubyEnumerable.java:852 filter_batch at /opt/logstash-2.3.4/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/pipeline.rb:265 worker_loop at /opt/logstash-2.3.4/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/pipeline.rb:223 start_workers at /opt/logstash-2.3.4/vendor/bundle/jruby/1.9/gems/logstash-core-2.3.4-java/lib/logstash/pipeline.rb:201

原因是沒有找到叫做foo的field,無法把該欄位值轉化成String型別。所以最好要加field if exist判斷。

2、判斷欄位是否存在,程式碼如下:

if ["foo"] {
  mutate {
    add_field => "bar" => "%{foo}"
  }
}