Class: Google::Logging::StructuredFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/google/logging/structured_formatter.rb

Overview

A log formatter that outputs the JSON-based structured logging format (cloud.google.com/logging/docs/structured-logging) understood by Google’s logging agent.

Constant Summary collapse

CLOUD_SEVERITY =
Hash.new { |_h, k| k }.merge(
  "WARN" => "WARNING",
  "FATAL" => "CRITICAL",
  "ANY" => "DEFAULT"
).freeze

Instance Method Summary collapse

Instance Method Details

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



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/google/logging/structured_formatter.rb', line 36

def call severity, time, progname, msg
  msg = Message.from msg
  time = msg.timestamp || time
  struct = {
    "severity" => CLOUD_SEVERITY[severity],
    "message" => msg.message,
    "timestamp" => {
      "seconds" => time.to_i,
      "nanos" => time.nsec
    }
  }
  struct.merge! msg.fields if msg.fields
  struct["logging.googleapis.com/sourceLocation"] = msg.source_location.to_h if msg.source_location
  struct["logging.googleapis.com/insertId"] = msg.insert_id if msg.insert_id
  struct["logging.googleapis.com/spanId"] = msg.span_id if msg.span_id
  struct["logging.googleapis.com/trace"] = msg.trace if msg.trace
  struct["logging.googleapis.com/traceSampled"] = msg.trace_sampled if msg.trace_sampled
  struct["logging.googleapis.com/labels"] = msg.labels if msg.labels
  struct["progname"] ||= progname if progname
  content = JSON.generate struct
  "#{content}\n"
end