1
0
mirror of https://github.com/meineerde/rackstash.git synced 2025-10-17 14:01:01 +00:00

Add JSON encoder

This commit is contained in:
Holger Just 2017-06-06 20:43:55 +02:00
parent 05f0faeedc
commit bf178ef36d
3 changed files with 64 additions and 0 deletions

View File

@ -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'

View File

@ -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

View File

@ -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