Skip to content

Instantly share code, notes, and snippets.

@SpringMT
Created July 8, 2020 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SpringMT/ec511321bcebba403ee467f2ae5734d0 to your computer and use it in GitHub Desktop.
Save SpringMT/ec511321bcebba403ee467f2ae5734d0 to your computer and use it in GitHub Desktop.
require "logger"
require "json"
require "active_support"
# https://github.com/yfuruyama/stackdriver-request-context-log/blob/master/stackdriver.go
# severityの変換
# https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/master/lib/fluent/plugin/out_google_cloud.rb#L1737
module Rrp
module Logger
class StackdriverFormatter < ::Logger::Formatter
include ActiveSupport::TaggedLogging::Formatter
DEFAULT_PARAMS_PROC = proc { {} }
attr_writer :params_proc
def initialize(*_args)
super
@params_proc = nil
end
def call(severity, time, progname, msg)
message_params = {}
message_params[:severity] = severity
message_params[:time] = time
message_params[:progname] = progname
message_params[:message] = msg2str(msg)
message_params.merge!(build_params)
# JSONで出力する
message_params.to_json + "\n"
end
def self.global_formatter
@global_formatter ||= self.new
end
private def build_params
params_proc = @params_proc || DEFAULT_PARAMS_PROC
params = params_proc.call
raise ArgumentError, "request_info should be a Hash. it was #{params.inspect}" unless params.is_a? Hash
params["logging.googleapis.com/trace"] = params[:request_id] if params[:request_id]
params
end
private def msg2str(msg)
case msg
when ::String
msg
when ::Exception
"#{msg.message} (#{msg.class}) #{msg.backtrace.inspect}"
else
msg.inspect
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment