Module: YetiLogger::MessageFormatters

Defined in:
lib/yeti_logger/message_formatters.rb

Overview

Helper class used to format messages for logging. These can be used directly, but are more convenient when used via YetiLogger

Constant Summary collapse

NUM_LINES_OF_EXCEPTIONS =
50

Class Method Summary collapse

Class Method Details

.build_log_message(klass, obj, exception = nil, backtrace_lines = NUM_LINES_OF_EXCEPTIONS) ⇒ String

Helper method used to build up a single log message string you can pass to the underlying logger implementation.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/yeti_logger/message_formatters.rb', line 12

def self.build_log_message(klass, obj, exception = nil, backtrace_lines = NUM_LINES_OF_EXCEPTIONS)
  msg = if obj.is_a?(Hash)
          if exception
            format_hash(obj.merge(exception_hash(exception, backtrace_lines)))
          else
            format_hash(obj)
          end
        elsif exception
          "#{obj} Exception: #{exception.message} "\
          "Error Class: #{exception.class.name} "\
          "#{format_backtrace(exception, backtrace_lines)}"
        else
          obj
        end
  "#{klass}: #{msg}"
end

.exception_hash(exception, lines = 20) ⇒ Hash

Create a hash with the exception message and backtrace. You can merge this into an existing hash if you’re logging key=value pairs.



67
68
69
70
71
72
73
# File 'lib/yeti_logger/message_formatters.rb', line 67

def self.exception_hash(exception, lines = 20)
  {
    :error => exception.message,
    :error_class => exception.class.name,
    :backtrace => format_backtrace(exception, lines)
  }
end

.format_backtrace(exception, lines = 20) ⇒ String

Format a backtrace by joining all lines into a single line and quoting the results. You can optionally specify how many lines to include.



80
81
82
# File 'lib/yeti_logger/message_formatters.rb', line 80

def self.format_backtrace(exception, lines = 20)
  exception.try(:backtrace).try(:take, lines).try(:join, ', ').inspect
end

.format_hash(hash) ⇒ String

Format a Hash into key=value pairs, separated by whitespace. TODO: support nested hashes by serializing to JSON?



34
35
36
37
38
# File 'lib/yeti_logger/message_formatters.rb', line 34

def self.format_hash(hash)
  hash.map do |k, v|
    "#{k}=#{quote_unquoted(v.to_s)}"
  end.join(' ')
end

.quote_unquoted(str) ⇒ String

Helper method to quote strings that need quoting (spaces in them, or embedded quotes) that have not already been quoted.



44
45
46
47
48
49
50
# File 'lib/yeti_logger/message_formatters.rb', line 44

def self.quote_unquoted(str)
  if str && (!needs_quoting?(str) || quoted?(str))
    str
  else
    str.inspect
  end
end