class GoogleCloudRun::LogEntry

Attributes

labels[RW]
location_line[RW]
location_method[RW]
location_path[RW]
message[RW]
project_id[RW]
request[RW]
severity[RW]
timestamp[RW]
user[RW]

Public Class Methods

new() click to toggle source
# File lib/google_cloud_run/entry.rb, line 14
def initialize
  @severity = G_DEFAULT
  @timestamp = Time.now.utc
  @insert_id = SecureRandom.uuid
end

Public Instance Methods

to_json() click to toggle source
# File lib/google_cloud_run/entry.rb, line 20
def to_json
  raise "labels must be hash" if !@labels.blank? && !@labels.is_a?(Hash)

  labels["user"] = @user unless @user.blank?

  j = {}

  j["logging.googleapis.com/insertId"] = @insert_id
  j["severity"] = Severity.to_s(Severity.mapping(@severity))
  j["message"] = @message.is_a?(String) ? @message.strip : @message.inspect
  j["timestampSeconds"] = @timestamp.to_i
  j["timestampNanos"] = @timestamp.nsec
  j["logging.googleapis.com/labels"] = @labels unless @labels.blank?

  if @request
    # https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#httprequest
    j["httpRequest"] = {}
    j["httpRequest"]["requestMethod"] = @request&.method.to_s
    j["httpRequest"]["requestUrl"] = @request&.url.to_s
    j["httpRequest"]["userAgent"] = @request&.headers["user-agent"].to_s unless @request&.headers["user-agent"].blank?
    j["httpRequest"]["remoteIp"] = @request&.remote_ip.to_s
    j["httpRequest"]["referer"] = @request&.headers["referer"].to_s unless @request&.headers["referer"].blank?

    trace, span, sample = GoogleCloudRun.parse_trace_context(@request&.headers["X-Cloud-Trace-Context"])
    j["logging.googleapis.com/trace"] = "projects/#{@project_id}/traces/#{trace}" unless trace.blank?
    j["logging.googleapis.com/spanId"] = span unless span.blank?
    j["logging.googleapis.com/trace_sampled"] = sample unless sample.nil?
  end

  if @location_path || @location_line || @location_method
    j["logging.googleapis.com/sourceLocation"] = {}
    j["logging.googleapis.com/sourceLocation"]["function"] = @location_method.to_s
    j["logging.googleapis.com/sourceLocation"]["file"] = @location_path.to_s
    j["logging.googleapis.com/sourceLocation"]["line"] = @location_line.to_i
  end

  j.to_json
end