Created
April 11, 2019 11:46
-
-
Save mathieujobin/2a705d7820f9f84bbcebdfc495872b38 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A module for instrumenting ActiveJob workers for Scout APM. | |
# | |
# These can appear under "Background Jobs" (default) or "Web Endpoints" in the UI, depending on the value of | |
# +SCOUT_TRANSACTION_TYPE+. | |
# | |
# Example usage: | |
# | |
# class BaseJob < ActiveJob::Base | |
# | |
# def perform(attributes) | |
# # Do work | |
# end | |
# # This MUST be included AFTER the perform method is defined. | |
# include ScoutApm::BackgroundJobIntegrations::ActiveJob::Instruments | |
# end | |
# | |
module ScoutApm | |
module BackgroundJobIntegrations | |
class ActiveJob | |
module Instruments | |
SCOUT_TRANSACTION_TYPE = 'Job' | |
def self.included(instrumented_class) | |
ScoutApm::Agent.instance.logger.debug "Instrumenting #{instrumented_class.inspect}" | |
instrumented_class.class_eval do | |
unless instrumented_class.method_defined?(:perform_without_scout_instruments) | |
alias_method :perform_without_scout_instruments, :perform | |
alias_method :perform, :perform_with_scout_instruments | |
end | |
end | |
end | |
def perform_with_scout_instruments(*args) | |
ensure_scout_started! | |
req = ScoutApm::RequestManager.lookup | |
started_queue = false | |
if scout_job_transaction? | |
req.start_layer(ScoutApm::Layer.new('Queue', self.queue_name)) | |
started_queue = true | |
end | |
req.start_layer(ScoutApm::Layer.new(SCOUT_TRANSACTION_TYPE, scout_job_name)) | |
started_transaction = true | |
begin | |
perform_without_scout_instruments(*args) | |
rescue | |
req.error! | |
raise | |
ensure | |
req.stop_layer if started_transaction | |
req.stop_layer if started_queue | |
end | |
end | |
def scout_job_name | |
self.class.to_s | |
end | |
def scout_job_transaction? | |
SCOUT_TRANSACTION_TYPE == 'Job' | |
end | |
def ensure_scout_started! | |
unless ScoutApm::Agent.instance.background_worker_running? | |
ScoutApm::Agent.instance.start(skip_app_server_check: true) | |
ScoutApm::Agent.instance.start_background_worker | |
end | |
end | |
end | |
end | |
end | |
end | |
Rails.application.config.after_initialize do | |
ActiveJob::Base.descendants.each do |subclass| | |
subclass.include(ScoutApm::BackgroundJobIntegrations::ActiveJob::Instruments) | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment