2018-08-14 22:39:34 +02:00
|
|
|
require 'active_job/logging'
|
|
|
|
require 'logstash-event'
|
|
|
|
|
2021-10-07 13:05:27 +02:00
|
|
|
class ActiveJob::ApplicationLogSubscriber < ::ActiveJob::LogSubscriber
|
2018-08-14 22:39:34 +02:00
|
|
|
def enqueue(event)
|
|
|
|
process_event(event, 'enqueue')
|
|
|
|
end
|
|
|
|
|
|
|
|
def enqueue_at(event)
|
|
|
|
process_event(event, 'enqueue_at')
|
|
|
|
end
|
|
|
|
|
|
|
|
def perform(event)
|
|
|
|
process_event(event, 'perform')
|
|
|
|
end
|
|
|
|
|
|
|
|
def perform_start(event)
|
|
|
|
process_event(event, 'perform_start')
|
|
|
|
end
|
|
|
|
|
|
|
|
def log(data)
|
|
|
|
event = LogStash::Event.new(data)
|
|
|
|
event['message'] = "#{data[:job_class]}##{data[:job_id]} at #{data[:scheduled_at]}"
|
|
|
|
logger.send(Lograge.log_level, event.to_json)
|
|
|
|
end
|
|
|
|
|
|
|
|
def logger
|
|
|
|
Lograge.logger.presence || super
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def process_event(event, type)
|
|
|
|
data = extract_metadata(event)
|
2018-12-24 16:32:23 +01:00
|
|
|
data.merge!(extract_exception(event))
|
2024-06-06 11:52:25 +02:00
|
|
|
data[:request_id] = Current.request_id if Current.request_id.present?
|
2018-12-24 16:33:46 +01:00
|
|
|
|
|
|
|
case type
|
|
|
|
when 'enqueue_at'
|
|
|
|
data.merge!(extract_scheduled_at(event))
|
|
|
|
when 'perform'
|
|
|
|
data.merge!(extract_duration(event))
|
|
|
|
end
|
2018-08-14 22:39:34 +02:00
|
|
|
|
|
|
|
tags = ['job', type]
|
2018-12-24 16:33:46 +01:00
|
|
|
if data[:exception]
|
|
|
|
tags.push('exception')
|
|
|
|
end
|
2018-08-14 22:39:34 +02:00
|
|
|
data[:tags] = tags
|
|
|
|
data[:type] = 'tps'
|
2022-01-18 12:49:23 +01:00
|
|
|
data[:source] = ENV['LOGRAGE_SOURCE']
|
2018-08-14 22:39:34 +02:00
|
|
|
|
|
|
|
log(data)
|
|
|
|
end
|
|
|
|
|
|
|
|
def extract_metadata(event)
|
|
|
|
{
|
|
|
|
job_id: event.payload[:job].job_id,
|
|
|
|
queue_name: queue_name(event),
|
|
|
|
job_class: event.payload[:job].class.to_s,
|
2018-10-01 14:06:08 +02:00
|
|
|
job_args: args_info(event.payload[:job])
|
2018-08-14 22:39:34 +02:00
|
|
|
}
|
|
|
|
end
|
|
|
|
|
|
|
|
def extract_duration(event)
|
|
|
|
{ duration: event.duration.to_f.round(2) }
|
|
|
|
end
|
|
|
|
|
|
|
|
def extract_exception(event)
|
|
|
|
event.payload.slice(:exception)
|
|
|
|
end
|
|
|
|
|
|
|
|
def extract_scheduled_at(event)
|
|
|
|
{ scheduled_at: scheduled_at(event) }
|
|
|
|
end
|
|
|
|
|
|
|
|
# The default args_info makes a string. We need objects to turn into JSON.
|
|
|
|
def args_info(job)
|
|
|
|
job.arguments.map { |arg| arg.try(:to_global_id).try(:to_s) || arg }
|
|
|
|
end
|
|
|
|
end
|