Class: Lumber::JsonFormatter

Inherits:
Log4r::BasicFormatter
  • Object
show all
Defined in:
lib/lumber/json_formatter.rb

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ JsonFormatter


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/lumber/json_formatter.rb', line 8

def initialize(hash={})
  mapping = hash['key_mapping'] || {}
  @key_mapping = Hash[mapping.collect {|k, v| [k.to_s, v.to_s.split('.')]}]

  @fields = {}
  fields = hash['fields'] || {}
  fields.each do |k, v|
    if v.kind_of? String
      @fields[k.to_s] = v.to_s.gsub(/#\{(.+)\}/) {|m| eval($1) }
    else
      @fields[k.to_s] = v
    end
  end

  @date_pattern = hash['date_pattern'] || '%H:%M:%S'
end

Instance Method Details

#format(logevent) ⇒ Object


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/lumber/json_formatter.rb', line 25

def format(logevent)
  data = @fields.dup

  assign_mapped_key(data, :timestamp, Time.now.strftime(@date_pattern))
  assign_mapped_key(data, :logger, logevent.fullname)
  assign_mapped_key(data, :level, Log4r::LNAMES[logevent.level].downcase)

  if logevent.data.kind_of? Exception
    message = "Caught #{logevent.data.class}"
    message << ": #{logevent.data.message}" if logevent.data.message
    assign_mapped_key(data, :message, message)
    assign_mapped_key(data, :exception, logevent.data.class.to_s)
    trace = logevent.data.backtrace if logevent.data.respond_to?(:backtrace)
    if trace
      assign_mapped_key(data, :backtrace, trace.join("\n\t"))
      assign_mapped_key(data, :file, trace[0].split(":")[0])
      assign_mapped_key(data, :line, trace[0].split(":")[1].to_i)
    end
  else
    assign_mapped_key(data, :message, format_object(logevent.data))
  end

  if logevent.tracer
    file, line, method = parse_caller(logevent.tracer[0])
    assign_mapped_key(data, :file, file)
    assign_mapped_key(data, :line, line)
    assign_mapped_key(data, :method, method)
  end

  gdc = Log4r::GDC.get
  if gdc && gdc != $0
    value = nil
    begin
      value = gdc.inspect
    rescue
    end
    assign_mapped_key(data, :gdc, value)
  end

  if Log4r::NDC.get_depth > 0
    value = []
    Log4r::NDC.clone_stack.each do |x|
      begin
        value << x.inspect
      rescue
      end
    end
    assign_mapped_key(data, :ndc, value)
  end

  mdc = Log4r::MDC.get_context
  if mdc && mdc.size > 0
    value = {}
    mdc.each do |k, v|
      begin
        value[k] = v.inspect
      rescue
      end
    end
    assign_mapped_key(data, :mdc, value)
  end

  "#{data.to_json}\n"
end