Class: Sidekiq::AppsignalContextMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/sidekiq/appsignal_context_middleware.rb

Overview

Middleware that adds rich context to AppSignal for Sidekiq jobs
This is automatically applied to all workers via config/initializers/sidekiq.rb

Context added:

  • namespace: 'background' (categorizes in AppSignal)
  • job_class: Worker class name
  • job_id: Sidekiq JID
  • queue: Queue name
  • retry_count: Number of retries so far
  • job_args: Sanitized job arguments

Instance Method Summary collapse

Instance Method Details

#call(worker, job, queue) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/sidekiq/appsignal_context_middleware.rb', line 16

def call(worker, job, queue)
  return yield unless defined?(Appsignal) && Appsignal.active?

  # Get the current AppSignal transaction
  transaction = Appsignal::Transaction.current

  if transaction && !transaction.nil_transaction?
    # Set namespace to 'background' for all Sidekiq jobs
    transaction.set_namespace('background')

    # Add job context as tags
    transaction.set_tags(
      job_class: worker.class.name,
      job_id: job['jid'],
      queue: queue,
      retry_count: job['retry_count'].to_i,
      created_at: job['created_at'] ? Time.at(job['created_at']).iso8601 : nil,
      enqueued_at: job['enqueued_at'] ? Time.at(job['enqueued_at']).iso8601 : nil
    )

    # Add sanitized job arguments as params (for debugging)
    if job['args'].present?
      sanitized_args = sanitize_args(job['args'])
      transaction.set_params(job_args: sanitized_args)
    end

    # Add batch context if this is a Sidekiq Pro batch job
    if job['bid'].present?
      transaction.set_tags(batch_id: job['bid'])
    end
  end

  yield
rescue StandardError => e
  # On error, add additional error context
  if transaction && !transaction.nil_transaction?
    transaction.set_tags(
      error_class: e.class.name,
      error_in_worker: worker.class.name
    )
  end
  raise
end