Skip to content

Commit fc430e9

Browse files
klausmeyerjordansissel
authored andcommitted
Add fallback_mode option to allow non-json source w/o warnings
Fixes #24
1 parent 34fccde commit fc430e9

File tree

2 files changed

+54
-2
lines changed

2 files changed

+54
-2
lines changed

lib/logstash/filters/json.rb

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,9 @@ class LogStash::Filters::Json < LogStash::Filters::Base
5959
# successful match
6060
config :tag_on_failure, :validate => :array, :default => ["_jsonparsefailure"]
6161

62+
# Allow to quietly fall-back to plain-text (aka skip the filter without warnings and tags)
63+
config :fallback_mode, :validate => :boolean, :default => false
64+
6265
def register
6366
# Nothing to do here
6467
end
@@ -72,8 +75,10 @@ def filter(event)
7275
begin
7376
parsed = LogStash::Json.load(source)
7477
rescue => e
75-
@tag_on_failure.each{|tag| event.tag(tag)}
76-
@logger.warn("Error parsing json", :source => @source, :raw => source, :exception => e)
78+
unless @fallback_mode
79+
@tag_on_failure.each{|tag| event.tag(tag)}
80+
@logger.warn("Error parsing json", :source => @source, :raw => source, :exception => e)
81+
end
7782
return
7883
end
7984

spec/filters/json_spec.rb

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,4 +175,51 @@
175175
end
176176
end
177177
end
178+
179+
describe "parse mixture of json an non-json content (fallback mode)" do
180+
subject(:filter) { LogStash::Filters::Json.new(config) }
181+
182+
let(:config) { {"source" => "message", "remove_field" => ["message"], "fallback_mode" => fallback_mode} }
183+
let(:event) { LogStash::Event.new("message" => message) }
184+
185+
before(:each) do
186+
allow(filter.logger).to receive(:warn)
187+
filter.register
188+
filter.filter(event)
189+
end
190+
191+
let(:message) { "this is not a json message" }
192+
193+
context "with fallback_mode off" do
194+
let(:fallback_mode) { false }
195+
196+
it "sends a warning to the logger" do
197+
expect(filter.logger).to have_received(:warn).with("Error parsing json", anything())
198+
end
199+
200+
it "keeps the source field" do
201+
expect(event["message"]).to eq message
202+
end
203+
204+
it "adds a parse-error tag" do
205+
expect(event["tags"]).to eq ["_jsonparsefailure"]
206+
end
207+
end
208+
209+
context "with fallback_mode on" do
210+
let(:fallback_mode) { true }
211+
212+
it "sends no warning" do
213+
expect(filter.logger).to_not have_received(:warn)
214+
end
215+
216+
it "keeps the source field" do
217+
expect(event["message"]).to eq message
218+
end
219+
220+
it "does not add a parse-error tag" do
221+
expect(event["tags"]).to be_nil
222+
end
223+
end
224+
end
178225
end

0 commit comments

Comments
 (0)