Skip to content

Instantly share code, notes, and snippets.

@dudo
Last active February 22, 2022 20:32
Show Gist options
  • Save dudo/604c30c881d9245ed7d4ebfc2bc72ffa to your computer and use it in GitHub Desktop.
Save dudo/604c30c881d9245ed7d4ebfc2bc72ffa to your computer and use it in GitHub Desktop.
Tracing via a macro
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
@dudo
Copy link
Author

dudo commented Feb 18, 2022

By default, the resource will be a combination of module/method.

class Thing
  extend Instrumentation

  instrument :instance_method

  def instance_method
    #
  end

  class << self
    extend Instrumentation

    instrument :klass_method

    def klass_method
      #
    end
  end
end
> Thing.klass_method
{:resource=>"Thing.klass_method", :operation=>"method.execution"}
=> nil
> Thing.new.instance_method
{:resource=>"Thing#instance_method", :operation=>"method.execution"}
=> nil

@dudo
Copy link
Author

dudo commented Feb 18, 2022

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