2018-12-28 18:05:51 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2019-04-01 12:20:41 -04:00
|
|
|
require "logger"
|
|
|
|
require "time"
|
2018-12-28 18:05:51 -05:00
|
|
|
|
|
|
|
module Sidekiq
|
2019-09-03 14:13:04 -04:00
|
|
|
module LogContext
|
2018-12-28 18:05:51 -05:00
|
|
|
def with_context(hash)
|
2018-12-29 10:54:05 -05:00
|
|
|
ctx.merge!(hash)
|
2018-12-28 18:05:51 -05:00
|
|
|
yield
|
|
|
|
ensure
|
2019-09-14 18:54:34 -04:00
|
|
|
hash.each_key { |key| ctx.delete(key) }
|
2018-12-29 10:54:05 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def ctx
|
|
|
|
Thread.current[:sidekiq_context] ||= {}
|
2018-12-28 18:05:51 -05:00
|
|
|
end
|
2019-09-03 14:13:04 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
class Logger < ::Logger
|
|
|
|
include LogContext
|
|
|
|
|
|
|
|
def initialize(*args)
|
|
|
|
super
|
|
|
|
self.formatter = Sidekiq.log_formatter
|
|
|
|
end
|
2018-12-28 18:05:51 -05:00
|
|
|
|
|
|
|
module Formatters
|
2018-12-29 10:54:05 -05:00
|
|
|
class Base < ::Logger::Formatter
|
|
|
|
def tid
|
2019-04-01 12:20:41 -04:00
|
|
|
Thread.current["sidekiq_tid"] ||= (Thread.current.object_id ^ ::Process.pid).to_s(36)
|
2018-12-28 18:05:51 -05:00
|
|
|
end
|
|
|
|
|
2018-12-29 10:54:05 -05:00
|
|
|
def ctx
|
|
|
|
Thread.current[:sidekiq_context] ||= {}
|
|
|
|
end
|
2018-12-28 18:05:51 -05:00
|
|
|
|
2018-12-29 10:54:05 -05:00
|
|
|
def format_context
|
2019-04-01 12:20:41 -04:00
|
|
|
" " + ctx.compact.map { |k, v| "#{k}=#{v}" }.join(" ") if ctx.any?
|
2018-12-29 10:54:05 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
class Pretty < Base
|
|
|
|
def call(severity, time, program_name, message)
|
|
|
|
"#{time.utc.iso8601(3)} pid=#{::Process.pid} tid=#{tid}#{format_context} #{severity}: #{message}\n"
|
2018-12-28 18:05:51 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
class WithoutTimestamp < Pretty
|
|
|
|
def call(severity, time, program_name, message)
|
2018-12-29 10:54:05 -05:00
|
|
|
"pid=#{::Process.pid} tid=#{tid}#{format_context} #{severity}: #{message}\n"
|
2018-12-28 18:05:51 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2018-12-29 10:54:05 -05:00
|
|
|
class JSON < Base
|
2018-12-28 18:05:51 -05:00
|
|
|
def call(severity, time, program_name, message)
|
2018-12-29 10:54:05 -05:00
|
|
|
hash = {
|
2018-12-28 18:05:51 -05:00
|
|
|
ts: time.utc.iso8601(3),
|
|
|
|
pid: ::Process.pid,
|
2018-12-29 10:54:05 -05:00
|
|
|
tid: tid,
|
|
|
|
lvl: severity,
|
2019-04-01 12:20:41 -04:00
|
|
|
msg: message,
|
2018-12-29 10:54:05 -05:00
|
|
|
}
|
|
|
|
c = ctx
|
|
|
|
hash["ctx"] = c unless c.empty?
|
|
|
|
|
|
|
|
Sidekiq.dump_json(hash) << "\n"
|
2018-12-28 18:05:51 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|