Class: PaulBunyan::JSONFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/paul_bunyan/json_formatter.rb

Constant Summary collapse

DATETIME_FORMAT =
'%Y-%m-%dT%H:%M:%S.%3N'

Instance Method Summary collapse

Instance Method Details

#add_metadata(metadata, **kw_metadata) ⇒ Object



8
9
10
# File 'lib/paul_bunyan/json_formatter.rb', line 8

def (, **)
  .merge!().merge!()
end

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



12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/paul_bunyan/json_formatter.rb', line 12

def call(severity, time, progname, msg)
   = .merge({
    "ts"       => time.utc.strftime(DATETIME_FORMAT),
    "unix_ts"  => time.to_f,
    "severity" => severity,
    "pid"      => $$,
  })
  ['program'] = progname if progname
  ['tags'] = current_tags unless current_tags.empty?

  message_data = format_message(msg)

  JSON::generate((, message_data)) + "\n"
end

#clear_metadata!Object



27
28
29
# File 'lib/paul_bunyan/json_formatter.rb', line 27

def clear_metadata!
  .clear
end

#clear_tags!Object



31
32
33
# File 'lib/paul_bunyan/json_formatter.rb', line 31

def clear_tags!
  current_tags.clear
end

#current_metadataObject



35
36
37
38
39
# File 'lib/paul_bunyan/json_formatter.rb', line 35

def 
   = @metadata_thread_key ||=
    "paul_bunyan_logging_metadata:#{self.object_id}"
  Thread.current[] ||= {}
end

#current_tagsObject



41
42
43
44
45
# File 'lib/paul_bunyan/json_formatter.rb', line 41

def current_tags
  tags_thread_key = @tags_thread_key ||=
    "paul_bunyan_logging_tags:#{self.object_id}"
  Thread.current[tags_thread_key] ||= []
end

#datetime_formatObject



52
53
54
# File 'lib/paul_bunyan/json_formatter.rb', line 52

def datetime_format
  DATETIME_FORMAT
end

#datetime_format=(value) ⇒ Object



47
48
49
50
# File 'lib/paul_bunyan/json_formatter.rb', line 47

def datetime_format=(value)
  # intentional nop because the whole point of this formatter is
  # to have a consistent machine parsable format :-P
end

#pop_tags(count = 1) ⇒ Object



56
57
58
# File 'lib/paul_bunyan/json_formatter.rb', line 56

def pop_tags(count = 1)
  current_tags.pop(count)
end

#push_tags(*tags) ⇒ Object



60
61
62
63
64
# File 'lib/paul_bunyan/json_formatter.rb', line 60

def push_tags(*tags)
  tags.flatten.reject{|t| t.nil? || t.to_s.strip == '' }.tap do |clean_tags|
    current_tags.concat(clean_tags)
  end
end

#remove_metadata(metadata = {}, **kw_metadata) ⇒ Object



66
67
68
# File 'lib/paul_bunyan/json_formatter.rb', line 66

def ( = {}, **)
  (.keys + .keys).each { |k| .delete(k) }
end

#tagged(*tags) ⇒ Object



70
71
72
73
74
75
# File 'lib/paul_bunyan/json_formatter.rb', line 70

def tagged(*tags)
  clean_tags = push_tags(tags)
  yield
ensure
  pop_tags(clean_tags.size)
end

#with_metadata(consumer_metadata = {}, **kw_metadata) ⇒ Object



77
78
79
80
81
82
# File 'lib/paul_bunyan/json_formatter.rb', line 77

def ( = {}, **)
  (, **)
  yield
ensure
  (, **)
end