2018-03-15 09:00:53 -07:00
|
|
|
# frozen_string_literal: true
|
2018-12-29 00:05:51 +01:00
|
|
|
|
2017-01-17 14:58:08 -08:00
|
|
|
module Sidekiq
|
|
|
|
class JobLogger
|
2019-04-01 18:20:41 +02:00
|
|
|
def initialize(logger = Sidekiq.logger)
|
2018-12-29 07:54:05 -08:00
|
|
|
@logger = logger
|
|
|
|
end
|
|
|
|
|
2017-01-17 14:58:08 -08:00
|
|
|
def call(item, queue)
|
2018-10-18 13:51:58 -07:00
|
|
|
start = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
|
2018-12-29 07:54:05 -08:00
|
|
|
@logger.info("start")
|
2018-12-29 00:05:51 +01:00
|
|
|
|
2017-05-08 12:50:36 -07:00
|
|
|
yield
|
2018-12-29 00:05:51 +01:00
|
|
|
|
2022-01-26 16:57:43 -08:00
|
|
|
Sidekiq::Context.add(:elapsed, elapsed(start))
|
|
|
|
@logger.info("done")
|
2017-05-08 12:50:36 -07:00
|
|
|
rescue Exception
|
2022-01-26 16:57:43 -08:00
|
|
|
Sidekiq::Context.add(:elapsed, elapsed(start))
|
|
|
|
@logger.info("fail")
|
2018-12-29 00:05:51 +01:00
|
|
|
|
2017-05-08 12:50:36 -07:00
|
|
|
raise
|
2017-01-17 14:58:08 -08:00
|
|
|
end
|
|
|
|
|
2019-09-25 15:53:04 -07:00
|
|
|
def prepare(job_hash, &block)
|
2018-12-29 00:05:51 +01:00
|
|
|
# If we're using a wrapper class, like ActiveJob, use the "wrapped"
|
|
|
|
# attribute to expose the underlying thing.
|
2018-12-29 07:54:05 -08:00
|
|
|
h = {
|
2021-05-24 12:29:45 -07:00
|
|
|
class: job_hash["display_class"] || job_hash["wrapped"] || job_hash["class"],
|
2020-03-17 13:38:48 -07:00
|
|
|
jid: job_hash["jid"]
|
2018-12-29 00:05:51 +01:00
|
|
|
}
|
2022-01-26 16:57:43 -08:00
|
|
|
h[:bid] = job_hash["bid"] if job_hash.has_key?("bid")
|
|
|
|
h[:tags] = job_hash["tags"] if job_hash.has_key?("tags")
|
2018-12-29 00:05:51 +01:00
|
|
|
|
2022-01-26 16:57:43 -08:00
|
|
|
Thread.current[:sidekiq_context] = h
|
|
|
|
level = job_hash["log_level"]
|
|
|
|
if level
|
|
|
|
@logger.log_at(level, &block)
|
|
|
|
else
|
|
|
|
yield
|
|
|
|
end
|
|
|
|
ensure
|
|
|
|
Thread.current[:sidekiq_context] = nil
|
2018-12-29 00:05:51 +01:00
|
|
|
end
|
|
|
|
|
2017-01-17 14:58:08 -08:00
|
|
|
private
|
|
|
|
|
|
|
|
def elapsed(start)
|
2018-10-18 13:51:58 -07:00
|
|
|
(::Process.clock_gettime(::Process::CLOCK_MONOTONIC) - start).round(3)
|
2017-01-17 14:58:08 -08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|