Logstash 中如何判断某个 tag 是否存在?
Logstash 判断 tag 用 in 运算符:if "tagname" in [tags];判断不存在用 not in 或否定。本文给出语法示例与 tags 数组的常用操作。
用 in 运算符:if "urgent" in [tags] { ... }——tags 是数组,in 检查元素是否在其中;取反用 if "urgent" not in [tags](或 !(...))。
基本用法
filter {
if "grokparsefailure" in [tags] {
# 解析失败的日志分流
mutate { add_field => { "parse_ok" => "false" } }
}
if "production" not in [tags] {
drop { } # 非生产日志直接丢弃
}
}
tags 的常用操作
# 添加 tag
mutate { add_tag => ["processed"] }
# 删除 tag
mutate { remove_tag => ["_dateparsefailure"] }
# 多条件
if ("error" in [tags]) and ("critical" in [tags]) { ... }
典型场景
- 用
_grokparsefailure标签兜底处理解析失败的日志; - Beats 输入常打
beats_input_codec_plain_applied等标签; - 自打标签做路由:
add_tag => ["to_es"],输出端if "to_es" in [tags]。
常见问题(FAQ)
Q:if [tags] == "urgent" 为什么不行? tags 是数组不是字符串——== 比较的是整个数组。
Q:tag 名带特殊字符? in 判断的是精确字符串匹配,含特殊字符照写即可。