Class: DohLogger::Formatter

Inherits:
Object show all
Defined in:
lib/doh/logger/formatter.rb

Instance Method Summary collapse

Constructor Details

#initialize(template) ⇒ Formatter

Returns a new instance of Formatter.



13
14
15
16
# File 'lib/doh/logger/formatter.rb', line 13

def initialize(template)
  @template = template
  @formats = {}
end

Instance Method Details

#register_format(field, &proc) ⇒ Object



18
19
20
# File 'lib/doh/logger/formatter.rb', line 18

def register_format(field, &proc)
  @formats[field] = proc
end

#replace(event) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/doh/logger/formatter.rb', line 22

def replace(event)
  result = @template.dup
  result.gsub!('%severity', DohLogger::severity_string(event.severity)) if result =~ /%severity/
  result.gsub!('%msg', event.msg) if result =~ /%msg/
  result.gsub!('%location', event.location) if result =~ /%location/
  result.gsub!('%time', event.time.strftime("%H:%M:%S.") << "%03d" % (event.time.usec / 1000)) if result =~ /%time/
  result.gsub!('%datetime', event.time.strftime("%Y-%m-%d %H:%M:%S.") << "%03d" % (event.time.usec / 1000)) if result =~ /%datetime/
  result.gsub!('%call_stack', event.call_stack.join("\n")) if result =~ /%call_stack/
  result.gsub!('%source_ip', event.source_ip) if result =~ /%source_ip/
  result.gsub!('%hostname', Socket.gethostname) if result =~ /%hostname/
  result.gsub!('%internal_ip', Doh::internal_ip) if result =~ /%internal_ip/
  result.gsub!('%exception', event.exception.nil? ? '' : "#{event.exception.class} -- #{event.exception}") if result =~ /%exception/

  @formats.each do |elem|
    result.gsub!(elem[0]) {elem[1].call(event)}
  end
  result
end