Class: RrxLogging::Formatter

Inherits:
Object
  • Object
show all
Defined in:
lib/rrx_logging/formatter.rb

Constant Summary collapse

MAX_MESSAGE_LENGTH =
2000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mode = :json, tags: nil) ⇒ Formatter

Returns a new instance of Formatter.



7
8
9
10
11
# File 'lib/rrx_logging/formatter.rb', line 7

def initialize(mode = :json, tags: nil)
  @mode         = mode
  @default_tags = tags || {}
  super()
end

Instance Attribute Details

#default_tagsObject (readonly)

Returns the value of attribute default_tags.



5
6
7
# File 'lib/rrx_logging/formatter.rb', line 5

def default_tags
  @default_tags
end

#modeObject (readonly)

Returns the value of attribute mode.



5
6
7
# File 'lib/rrx_logging/formatter.rb', line 5

def mode
  @mode
end

Instance Method Details

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

Parameters:

  • severity (String)
  • timestamp (Time)
  • progname (String)
  • msg (String)


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/rrx_logging/formatter.rb', line 17

def call(severity, timestamp, progname, msg)
  msg = msg.to_s.strip

  if @mode == :json
    data        = {
      time:  timestamp,
      level: severity,
      log:   msg
    }
    data[:name] = progname if progname
    data[:log]  = msg.truncate(MAX_MESSAGE_LENGTH) if msg.length > MAX_MESSAGE_LENGTH
    data.merge!(current_tags)
    "#{data.to_json}\n"
  else
    tags = current_tags.map { |k, v| "[#{k}=#{v}]" }
    "%s %s %s %s%s%s\n" % [
      timestamp.strftime('%Y-%m-%d'),
      timestamp.strftime('%H:%M:%S.%L'),
      severity,
      progname ? "#{progname}: " : '',
      msg,
      tags.empty? ? '' : ' %s' % tags.join('')
    ]
  end
end

#clear_tags!Object



51
52
53
# File 'lib/rrx_logging/formatter.rb', line 51

def clear_tags!
  current_tags.clear
end

#current_tagsHash

Returns:

  • (Hash)


56
57
58
# File 'lib/rrx_logging/formatter.rb', line 56

def current_tags
  Thread.current[thread_key] ||= @default_tags
end

#current_tags=(val) ⇒ Object

Parameters:

  • val (Hash)


61
62
63
# File 'lib/rrx_logging/formatter.rb', line 61

def current_tags=(val)
  Thread.current[thread_key] = val
end

#thread_keyString

Returns:

  • (String)


66
67
68
69
# File 'lib/rrx_logging/formatter.rb', line 66

def thread_key
  # We use our object ID here to avoid conflicting with other instances
  @thread_key ||= "activesupport_tagged_logging_tags:#{object_id}"
end

#with_tags(**tags) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/rrx_logging/formatter.rb', line 43

def with_tags(**tags)
  old_tags          = current_tags
  self.current_tags = old_tags.merge(tags)
  yield self
ensure
  self.current_tags = old_tags
end