Class: Startback::Support::LogFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/startback/support/log_formatter.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{
  pretty_print: nil
}

Instance Method Summary collapse

Constructor Details

#initialize(options = {}, redactor = default_redactor) ⇒ LogFormatter

Returns a new instance of LogFormatter.



9
10
11
12
13
# File 'lib/startback/support/log_formatter.rb', line 9

def initialize(options = {}, redactor = default_redactor)
  @options = DEFAULT_OPTIONS.merge(options)
  @options[:pretty_print] = auto_pretty_print unless @options.has_key?(:pretty_print)
  @redactor = redactor
end

Instance Method Details

#call(severity, time, progname, msg) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/startback/support/log_formatter.rb', line 19

def call(severity, time, progname, msg)
  msg = { message: msg } if msg.is_a?(String)
  msg = { error: msg } if msg.is_a?(Exception)
  data = {
    severity: severity,
    time: time
  }.merge(msg)
   .merge(error: error_to_json(msg[:error], severity))
   .compact
  data = @redactor.redact(data)
  if pretty_print?
    JSON.pretty_generate(data) << "\n"
  else
    data.to_json << "\n"
  end
end

#error_to_json(error, severity = nil) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/startback/support/log_formatter.rb', line 36

def error_to_json(error, severity = nil)
  return error if error.nil?
  return error if error.is_a?(String)
  return error.to_s unless error.is_a?(Exception)

  backtrace = error.backtrace[0..25] if severity == "FATAL"
  causes = error.causes.map{|c| error_to_json(c) } if error.respond_to?(:causes)
  causes = nil if causes && causes.empty?
  {
    message: error.message,
    backtrace: backtrace,
    causes: causes
  }.compact
end

#pretty_print?Boolean

Returns:

  • (Boolean)


15
16
17
# File 'lib/startback/support/log_formatter.rb', line 15

def pretty_print?
  !!@options[:pretty_print]
end