diff --git a/lib/rackstash/encoders.rb b/lib/rackstash/encoders.rb new file mode 100644 index 0000000..abacfa2 --- /dev/null +++ b/lib/rackstash/encoders.rb @@ -0,0 +1,6 @@ +# Copyright 2017 Holger Just +# +# This software may be modified and distributed under the terms +# of the MIT license. See the LICENSE.txt file for details. + +require 'rackstash/encoders/json' diff --git a/lib/rackstash/encoders/json.rb b/lib/rackstash/encoders/json.rb new file mode 100644 index 0000000..25b475f --- /dev/null +++ b/lib/rackstash/encoders/json.rb @@ -0,0 +1,29 @@ +# Copyright 2017 Holger Just +# +# This software may be modified and distributed under the terms +# of the MIT license. See the LICENSE.txt file for details. + +require 'json' + +module Rackstash + module Encoders + # The JSON encoder formats the log event as a single-line JSON string. The + # resulting JSON string contains all data exposed by the buffer. Leading + # and trailing whitespace on the `"message"` field will be removed. + # + # The resulting string is in the JSON format native to Logstash. You can + # thus ship your logs directly to Logstash without further processing by + # using Logstash's [json codec](https://www.elastic.co/guide/en/logstash/current/plugins-codecs-json.html) + # on the input definition. + # + # Most {Adapters} default to use this codec. + class JSON + # @param event [Hash] a log event as produced by the {Flow} + # @return [String] the event as a single-line JSON string + def encode(event) + event[FIELD_MESSAGE].strip! + ::JSON.dump(event) + end + end + end +end diff --git a/spec/rackstash/encoders/json_spec.rb b/spec/rackstash/encoders/json_spec.rb new file mode 100644 index 0000000..be3d362 --- /dev/null +++ b/spec/rackstash/encoders/json_spec.rb @@ -0,0 +1,29 @@ +# Copyright 2017 Holger Just +# +# This software may be modified and distributed under the terms +# of the MIT license. See the LICENSE.txt file for details. + +require 'spec_helper' + +require 'rackstash/encoders/json' + +describe Rackstash::Encoders::JSON do + let(:encoder) { Rackstash::Encoders::JSON.new } + + describe '#encode' do + it 'formats the passed event hash as a JSON string' do + event = { 'hello' => 'world', 'message' => 'hello' } + expect(encoder.encode(event)).to eql '{"hello":"world","message":"hello"}' + end + + it 'formats newlines as \n' do + event = { 'message' => "text\nwith\nnewlines" } + expect(encoder.encode(event)).to eql '{"message":"text\nwith\nnewlines"}' + end + + it 'rstrips the message' do + event = { 'message' => "line1\nline2\n \n\t\n" } + expect(encoder.encode(event)).to eql '{"message":"line1\nline2"}' + end + end +end