Class: YetiLogger::CustomFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/yeti_logger/custom_formatter.rb

Overview

CustomFormatter is a custom Rails log formatter. It has support for adding arbitrary tags to every log created by the Rails logger. Tag values are generated at log creation time.

Instance Method Summary collapse

Constructor Details

#initialize(tags = {}) ⇒ CustomFormatter



6
7
8
9
# File 'lib/yeti_logger/custom_formatter.rb', line 6

def initialize(tags = {})
  super()
  @tags = tags
end

Instance Method Details

#add_tags(tags) ⇒ Object



12
13
14
# File 'lib/yeti_logger/custom_formatter.rb', line 12

def add_tags(tags)
  @tags.merge!(tags)
end

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



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/yeti_logger/custom_formatter.rb', line 20

def call(severity, time, progname, msg)
  timestamp = %w(production staging).include?(ENV['RAILS_ENV']) ? "" : "#{Time.now.iso8601(3)} "
  pid = Process.pid
  msg = msg.inspect unless msg.is_a?(String)
  msg = "#{msg}\n" unless msg[-1] == ?\n
  log_str = "#{timestamp}pid=#{pid}"

  tag_str = @tags.map { |k, v|
    value = v.call
    "#{k}=#{value}" unless value.to_s.empty?
  }.compact.join(' ')

  "#{log_str}#{tag_str.empty? ? '' : ' ' + tag_str} [#{severity}] - #{msg}"
end