Class: Labkit::Logging::JsonLogger

Inherits:
Logger
  • Object
show all
Defined in:
lib/labkit/logging/json_logger.rb

Constant Summary collapse

RESERVED_LOG_KEYS =

We should also reject log keys coming from Labkit::Context, but we cannot do this without breaking clients currently. This is tracked in gitlab.com/gitlab-org/ruby/gems/labkit-ruby/-/issues/35

[
  :environment,
  :host,
  :shard,
  :stage,
  :subcomponent,
  :tier,
  :type,
].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, level: JsonLogger.log_level) ⇒ JsonLogger

Returns a new instance of JsonLogger.



35
36
37
# File 'lib/labkit/logging/json_logger.rb', line 35

def initialize(path, level: JsonLogger.log_level)
  super
end

Class Method Details

.exclude_context!Object



26
27
28
29
# File 'lib/labkit/logging/json_logger.rb', line 26

def self.exclude_context!
  @exclude_context = true
  self
end

.exclude_context?Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/labkit/logging/json_logger.rb', line 31

def self.exclude_context?
  !!@exclude_context
end

.log_level(fallback: ::Logger::DEBUG) ⇒ Object



22
23
24
# File 'lib/labkit/logging/json_logger.rb', line 22

def self.log_level(fallback: ::Logger::DEBUG)
  ENV.fetch("GITLAB_LOG_LEVEL", fallback)
end

Instance Method Details

#format_message(severity, timestamp, progname, message) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/labkit/logging/json_logger.rb', line 39

def format_message(severity, timestamp, progname, message)
  data = default_attributes
  data[:severity] = severity
  data[:time] = timestamp.utc.iso8601(3)

  if self.class.exclude_context?
    data[Labkit::Correlation::CorrelationId::LOG_KEY] = Labkit::Correlation::CorrelationId.current_id
  else
    data.merge!(Labkit::Context.current.to_h)
  end

  case message
  when String
    data[:message] = message
  when Hash
    reject_reserved_log_keys!(message)
    data.merge!(message)
  end

  dump_json(data) << "\n"
end