Skip to content

Commit 4fb72d8

Browse files
committed
Support dynamic target field names.
It's conceivable that one would want the target field name to be chosen dynamically using the contents of another field, so pass the target option value through sprintf.
1 parent 80f1795 commit 4fb72d8

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

lib/logstash/filters/json.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,12 @@ class LogStash::Filters::Json < LogStash::Filters::Base
5252
# JSON in the value of the `source` field will be expanded into a
5353
# data structure in the `target` field.
5454
#
55+
# The string in the `target` option may contain dynamic sprintf-style
56+
# field references, i.e. the contents of one field can be used to choose
57+
# the name of the target field. Dynamic field references can only refer
58+
# to already existing fields, so the JSON string being parsed can't
59+
# contain the name of the target field.
60+
#
5561
# NOTE: if the `target` field already exists, it will be overwritten!
5662
config :target, :validate => :string
5763

@@ -83,7 +89,7 @@ def filter(event)
8389
end
8490

8591
if @target
86-
event.set(@target, parsed)
92+
event.set(event.sprintf(@target), parsed)
8793
else
8894
unless parsed.is_a?(Hash)
8995
@tag_on_failure.each{|tag| event.tag(tag)}

spec/filters/json_spec.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,23 @@
4141
end
4242
end
4343

44+
describe "parse message into a dynamically named target field" do
45+
config <<-CONFIG
46+
filter {
47+
json {
48+
# Parse message as JSON, store the results in the field named
49+
# by the contents of the 'target' field'
50+
source => "message"
51+
target => "%{target}"
52+
}
53+
}
54+
CONFIG
55+
56+
sample({"target" => "data", "message" => '{ "hello": "world" }'}) do
57+
insist { subject.get("[data][hello]") } == "world"
58+
end
59+
end
60+
4461
describe "tag invalid json" do
4562
config <<-CONFIG
4663
filter {

0 commit comments

Comments
 (0)