您可以使用 LogCollector 的 json_extract 插件,指定 JSONPath 表达式从指定 JSON 内容中提取一个或多个值,并将其作为一个新的 JSON 数组添加到日志中。
说明
LogCollector V2.2.5 及后续版本支持该插件。如何查看 LogCollector 版本,请参考2 查看软件版本。
名称 | 类型 | 是否必选 | 说明 |
---|---|---|---|
field | String | 是 | 包含 JSON 字符串的字段名称。 |
new_field | String | 是 | 存储提取出的值的新字段名称。 |
json_path | String | 是 | 从 |
keep_source | Boolean | 否 | 是否保留原始的 |
如 JSON 内容:
{ "name": {"first": "Tom", "last": "Anderson"}, "age":37, "children": ["Sara","Alex","Jack"], "fav.movie": "Deer Hunter", "friends": [ {"first": "Dale", "last": "Murphy", "age": 44, "nets": ["ig", "fb", "tw"]}, {"first": "Roger", "last": "Craig", "age": 68, "nets": ["fb", "tw"]}, {"first": "Jane", "last": "Murphy", "age": 47, "nets": ["ig", "tw"]} ] }
JSONPath 表达式及其匹配的值:
JSONPath 表达式 | 匹配的值 |
---|---|
name.last | "Anderson" |
name.first | "Tom" |
age | 37 |
children | ["Sara","Alex","Jack"] |
children.0 | "Sara" |
children.1 | "Alex" |
friends.1 | {"first": "Roger", "last": "Craig", "age": 68, "nets": ["fb", "tw"]} |
friends.1.first | "Roger" |
friends.#.age | [44,68,47] |
日志内容如下,其中 request_body
字段的值是 JSON 字符串:
{ "timestamp": "2023-10-26T10:30:00Z", "level": "INFO", "source_ip": "192.168.1.100", "request_body": "{\"user\": {\"id\": \"usr_123\", \"username\": \"alice\", \"attributes\": {\"roles\": [\"administrator\", \"power_user\"], \"department\": \"engineering\"}}, \"action\": \"update_profile\"}" }
LogCollector 的 json_extract 插件处理器配置:
从request_body
字段的 JSON 内容中,以 JSONPath 表达式为user.attributes.roles
提取值,并将值存储至user_roles
字段中。
{ "processors": [ { "json_extract": { "field": "request_body", "json_path": "user.attributes.roles", "new_field": "user_roles" } } ] }
处理结果:
{ "timestamp": "2023-10-26T10:30:00Z", "level": "INFO", "source_ip": "192.168.1.100", "user_roles": ["administrator","power_user"] }