Skip to content

Commit

Permalink
introduce an opinionatedly better statsd helper that gives you access…
Browse files Browse the repository at this point in the history
… to all your variables
  • Loading branch information
raginpirate committed Feb 3, 2025
1 parent 6fd8c49 commit b779aed
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions lib/statsd/instrument.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,18 @@ def generate_metric_name(name, callee, *args)
# Generates the tags for an instrumented method.
# @private
# @return [Array[String]]
def generate_tags(tags, callee, *args)
def generate_tags(tags, callee, result=nil, *args)
return if tags.nil?

tags.respond_to?(:call) ? tags.call(callee, args) : tags
if tags.respond_to?(:call)
if result.nil?
tags.call(callee, args)
else
tags.call(callee, args, result)
end
else
tags
end
end

# Even though this method is considered private, and is no longer used internally,
Expand Down Expand Up @@ -218,6 +226,23 @@ def statsd_count(method, name, sample_rate: nil, tags: nil, no_prefix: false, cl
end
end

def statsd_count_but_better(method, name, sample_rate: nil, tags: nil, no_prefix: false, client: nil)
add_to_method(method, name, :count_but_better) do
define_method(method) do |*args, &block|
error = nil
result = super(*args, &block)
rescue => e
error = e
raise
ensure
client ||= StatsD.singleton_client
generated_metric_name = StatsD::Instrument.generate_metric_name(name, self, *args)
generated_tags = StatsD::Instrument.generate_tags(tags, self, result, *args)
client.increment(generated_metric_name, sample_rate: sample_rate, tags: generated_tags, no_prefix: no_prefix)
end
end
end

# Removes StatsD counter instrumentation from a method
# @param method [Symbol] The method to remove instrumentation from.
# @param name [String] The name of the metric that was used.
Expand Down

0 comments on commit b779aed

Please sign in to comment.