Skip to content

Commit

Permalink
Add LTSV formatter and its spec
Browse files Browse the repository at this point in the history
  • Loading branch information
takashi committed Jul 6, 2015
1 parent 44a5e8c commit ec5102e
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .travis.yml
Expand Up @@ -7,6 +7,9 @@ rvm:
- jruby
- jruby-head
- rbx-2
matrix:
allow_failures:
- rvm: jruby-head
env:
global:
- JRUBY_OPTS='-J-XX:+TieredCompilation -J-XX:TieredStopAtLevel=1 -J-Djruby.compile.mode=OFF -J-Djruby.compile.invokedynamic=false'
Expand Down
1 change: 1 addition & 0 deletions lib/lograge.rb
Expand Up @@ -6,6 +6,7 @@
require 'lograge/formatters/l2met'
require 'lograge/formatters/lines'
require 'lograge/formatters/logstash'
require 'lograge/formatters/ltsv'
require 'lograge/formatters/raw'
require 'lograge/log_subscriber'
require 'active_support/core_ext/module/attribute_accessors'
Expand Down
43 changes: 43 additions & 0 deletions lib/lograge/formatters/ltsv.rb
@@ -0,0 +1,43 @@
module Lograge
module Formatters
class LTSV
def call(data)
fields = fields_to_display(data)

event = fields.map { |key| format(key, data[key]) }
event.join('\t')
end

def fields_to_display(data)
data.keys
end

def format(key, value)
if key == :error
# Exactly preserve the previous output
# Parsing this can be ambigious if the error messages contains
# a single quote
value = "'#{escape value}'"
else
# Ensure that we always have exactly two decimals
value = Kernel.format('%.2f', value) if value.is_a? Float
end

"#{key}:#{value}"
end

private

def escape(string)
value = string.is_a?(String) ? string.dup : string.to_s

value.gsub!('\\', '\\\\')
value.gsub!('\n', '\\n')
value.gsub!('\r', '\\r')
value.gsub!('\t', '\\t')

value
end
end
end
end
29 changes: 29 additions & 0 deletions spec/formatters/ltsv_spec.rb
@@ -0,0 +1,29 @@
require 'lograge'

describe Lograge::Formatters::LTSV do
let(:payload) do
{
custom: 'data',
status: 200,
method: 'GET',
path: '/',
controller: 'welcome',
action: 'index',
will_escaped: '\t'
}
end

subject { described_class.new.call(payload) }

it "includes the 'controller' key:value" do
expect(subject).to include('controller:welcome')
end

it "includes the 'action' key:value" do
expect(subject).to include('action:index')
end

it 'escapes escape sequences as value' do
expect(subject).to include('will_escaped:\\t')
end
end

0 comments on commit ec5102e

Please sign in to comment.