Logstash Ruby Filter解析JSON并将键值插入对应JSON块的方法
Got it, let's fix this Logstash Ruby filter for you. Here's the corrected code along with explanations to make sure it does exactly what you need:
Solution Code
filter { ruby { code => ' # Iterate over all top-level key-value pairs in the event event.to_hash.each do |ip, details| # Skip Logstash built-in fields to avoid unintended processing next if ["@timestamp", "@version"].include?(ip) # Add the "host" field to the child object, using the IP as its value details["host"] = ip # Optional: Uncomment below to split each IP's data into a separate Logstash event # event.spawn(details) end ' } }
How It Works
Let's break down what each part does:
- Iterate over top-level keys:
event.to_hash.each do |ip, details|grabs every key-value pair in your input. Theipvariable holds your top-level IP address, anddetailsis the child object associated with it. - Skip built-in fields: We skip Logstash's auto-added fields like
@timestampand@versionso we don't accidentally treat them as IP addresses. You can add more fields to this list if your input has other non-IP top-level keys. - Add the
hostfield:details["host"] = ipdirectly injects the IP address into the child object as thehostfield—exactly what you asked for. - Optional: Split into separate events: If you want each IP's data to become its own independent Logstash event (super useful for indexing into Elasticsearch or other destinations), uncomment the
event.spawn(details)line. This will create a new event for every IP, with a flat structure that includes thehostfield.
Example Input/Output
Sample Input
{ "192.168.1.1": {"status": "up", "response_time": 0.2}, "10.0.0.5": {"status": "down", "response_time": null} }
Output (Keeping Original Top-Level Structure)
{ "192.168.1.1": {"status": "up", "response_time": 0.2, "host": "192.168.1.1"}, "10.0.0.5": {"status": "down", "response_time": null, "host": "10.0.0.5"}, "@timestamp": "2024-05-20T14:22:00.123Z", "@version": "1" }
Output (With Split Events)
Each IP becomes a standalone event:
{"status": "up", "response_time": 0.2, "host": "192.168.1.1", "@timestamp": "...", "@version": "1"} {"status": "down", "response_time": null, "host": "10.0.0.5", "@timestamp": "...", "@version": "1"}
内容的提问来源于stack exchange,提问作者Darshan
相关产品推荐
相关产品推荐

