Class: Wurk::JobLogger

Inherits:
Object
  • Object
show all
Defined in:
lib/wurk/job_logger.rb

Overview

Wraps the per-job execution span. Logs “start”/“done”/“fail” at INFO, pushes :elapsed into Wurk::Context so the logger formatter can pick it up, and prepares the thread-local context hash (jid, class, plus config).

Two entry points, called from Processor#process in this order:

1. prepare(job_hash) { ... }  → sets thread-local context, applies
   per-job log_level, yields to the rest of dispatch.
2. call(item, queue) { ... }  → wraps the actual perform with the
   start/done/fail log line trio and the elapsed-ms measurement.

Skipping default logging is controlled by config; the prepare step still runs so context/log_level still apply.

Spec: docs/target/sidekiq-free.md §18.

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ JobLogger

Returns a new instance of JobLogger.



20
21
22
23
24
# File 'lib/wurk/job_logger.rb', line 20

def initialize(config)
  @config = config
  @logger = @config.logger
  @skip = !!@config[:skip_default_job_logging]
end

Instance Method Details

#call(_item, _queue) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/wurk/job_logger.rb', line 26

def call(_item, _queue)
  start = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
  @logger.info { 'start' } unless @skip

  yield

  Wurk::Context.add(:elapsed, elapsed(start))
  @logger.info { 'done' } unless @skip
rescue Exception # rubocop:disable Lint/RescueException
  Wurk::Context.add(:elapsed, elapsed(start))
  @logger.info { 'fail' } unless @skip
  raise
end

#prepare(job_hash, &block) ⇒ Object

Sets thread-local context for the duration of ‘block`, optionally under a per-job log level. ActiveJob-wrapped jobs expose the real class via the “wrapped” key — log that, not the wrapper.



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/wurk/job_logger.rb', line 43

def prepare(job_hash, &block)
  h = {
    jid: job_hash['jid'],
    class: job_hash['wrapped'] || job_hash['class']
  }
  @config[:logged_job_attributes].each do |attr|
    h[attr.to_sym] = job_hash[attr] if job_hash.key?(attr)
  end

  level = job_hash['log_level']
  Wurk::Context.with(h) do
    if level
      @logger.with_level(level, &block)
    else
      yield
    end
  end
end