我有进入ELK堆栈的日志文件。我想复制一个字段(foo)以便在其上执行各种突变,但是字段(foo)并不总是存在。
如果foo不存在,则仍然会创建bar,但会为其分配文字字符串"%{foo}"
如果字段存在,我怎样才能执行变异?
我正在尝试做这样的事情。
if ["foo"] {
mutate {
add_field => "bar" => "%{foo}
}
}
答案 0 :(得分:67)
检查字段foo是否存在:
1)对于数字类型字段,请使用:
if ([foo]) {
...
}
2)对于除布尔之类的数字以外的类型,字符串使用:
if ("" in [foo]) {
...
}
答案 1 :(得分:32)
“foo”是一个文字字符串。
[foo]是一个字段。
# technically anything that returns 'true', so good for numbers and basic strings:
if [foo] {
}
# contains a value
if [foo] =~ /.+/ {
}
答案 2 :(得分:16)
在Logstash 2.2.2上,("" in [field])
构造似乎不适合我。
if ![field] { }
对于非数字字段。
答案 3 :(得分:7)
现在是2020年,以上答案均不完全正确。自2014年以来,我一直在使用logstash,并且filter中的表达式过去,现在和将来都会是一件事情...
例如,您可能有一个具有false
值的布尔字段,并且使用上述解决方案,您可能不知道false
是该字段的值还是表达式的结果值,因为该字段不存在。
我认为logstash的所有版本都支持[@metadata]
字段。也就是说,对于输出插件不可见的字段,仅存在于过滤状态。所以这就是我要解决的问题:
filter {
mutate {
# we use a "temporal" field with a predefined arbitrary known value that
# lives only in filtering stage.
add_field => { "[@metadata][testField_check]" => "unknown arbitrary value" }
# we copy the field of interest into that temporal field.
# If the field doesn't exist, copy is not executed.
copy => { "testField" => "[@metadata][testField_check]" }
}
# now we now if testField didn't exists, our field will have
# the initial arbitrary value
if [@metadata][testField_check] == "unknown arbitrary value" {
# just for debugging purpouses...
mutate { add_field => { "FIELD_DID_NOT_EXISTED" => true }}
} else {
# just for debugging purpouses...
mutate { add_field => { "FIELD_DID_ALREADY_EXISTED" => true }}
}
}
我一直在努力处理logstash中的表达式。我的old solution一直工作到版本7。这是用于布尔字段的,例如:
filter {
# if the field does not exists, `convert` will create it with "false" string. If
# the field exists, it will be the boolean value converted into string.
mutate { convert => { "field" => "string" } }
# This condition breaks on logstash > 7 (see my bug report). Before version 7,
# this condition will be true if a boolean field didn't exists.
if ![field] {
mutate { add_field => { "field" => false } }
}
# at this stage, we are sure field exists, so make it boolean again
mutate { convert => { "field" => "boolean" } }
}