Last active
February 22, 2022 20:32
-
-
Save dudo/604c30c881d9245ed7d4ebfc2bc72ffa to your computer and use it in GitHub Desktop.
Tracing via a macro
This file contains hidden or 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
module Instrumentation | |
DEFAULT_OPERATION = 'method.execution' | |
def self.trace(operation: DEFAULT_OPERATION, resource:, **options) | |
options.merge!(resource: resource).compact! | |
Datadog.tracer.trace(operation, options) do |span| | |
Datadog::Analytics.set_measured(span) | |
yield | |
end | |
rescue StandardError | |
puts options.merge(operation: operation) | |
yield | |
end | |
def instrument(method_name, on_error: nil, **options) | |
proxy = Module.new | |
proxy.define_method(method_name) do |*args, &block| | |
instance_options = options.each_with_object(options.dup) do |(k, v), o| | |
o[k] = instance_exec(&v) if v.is_a?(Proc) | |
end | |
instance_options[:resource] ||= is_a?(Module) ? "#{self}.#{method_name}" : "#{self.class}##{method_name}" | |
Instrumentation.trace(**options, on_error: on_error) do | |
super(*args, &block) | |
end | |
end | |
prepend proxy | |
end | |
end |
Arguments can be static strings/symbols, but importantly, a lambda can be passed to give dynamic values to arguments at runtime.
class Thing
extend Instrumentation
instrument :instance_method, resource: -> { some_method }
def instance_method
#
end
private
def some_method
'foo'
end
end
> Thing.new.instance_method
{:resource=>"foo", :operation=>"method.execution"}
=> nil
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
By default, the resource will be a combination of module/method.