class Logfoo::LogfmtFormatter

Constants

FLOAT_FORMAT
IGNORED_KEYS
STACKTRACE_RE
UNESCAPED_STRING

Public Instance Methods

call(line) click to toggle source
# File lib/logfoo/formatters/logfmt_formatter.rb, line 10
def call(line)
  case line
  when ErrLine, LogLine
    format_line(line)
  else
    "#{remove_nl line.to_s}\n"
  end
end

Private Instance Methods

format_hash(attrs) click to toggle source
# File lib/logfoo/formatters/logfmt_formatter.rb, line 29
def format_hash(attrs)
  attrs.inject([]) do |ac, (k,v)|
    if !IGNORED_KEYS.include?(k) && !(v == nil || v == "")
      new_value = sanitize(k, v)
      ac << "#{k}=#{new_value}"
    end
    ac
  end.join(" ")
end
format_line(line) click to toggle source
# File lib/logfoo/formatters/logfmt_formatter.rb, line 25
def format_line(line)
  "#{remove_nl format_hash(line.to_h)}\n"
end
format_stacktrace(stack) click to toggle source
# File lib/logfoo/formatters/logfmt_formatter.rb, line 39
def format_stacktrace(stack)
  stack =
    stack.inject([]) do |ac, line|
      if line.match(STACKTRACE_RE)
        ac.push "[#{$1}:#{$2}:#{$3}]"
      end
      ac
    end
  if stack.any?
    "\"#{stack.join("")}\""
  end
end
maybe_quote(s) click to toggle source
# File lib/logfoo/formatters/logfmt_formatter.rb, line 79
def maybe_quote(s)
  s =~ UNESCAPED_STRING ? s : quote(s)
end
quote(s) click to toggle source
# File lib/logfoo/formatters/logfmt_formatter.rb, line 75
def quote(s)
  s.inspect
end
remove_nl(s) click to toggle source
# File lib/logfoo/formatters/logfmt_formatter.rb, line 21
def remove_nl(s)
  s.tr("\n", ' ')
end
sanitize(k, v) click to toggle source
# File lib/logfoo/formatters/logfmt_formatter.rb, line 52
def sanitize(k, v)
  case v
  when ::Array
    if k == :stacktrace
      format_stacktrace(v)
    else
      maybe_quote v.map{|i| i.to_s }.join(",")
    end
  when ::Integer, ::Symbol
    v.to_s
  when ::Float
    FLOAT_FORMAT % v
  when ::TrueClass
    :t
  when ::FalseClass
    :f
  when ::Time
    v.utc.iso8601
  else
    maybe_quote v.to_s
  end
end