Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

introduce an opinionatedly better statsd helper that gives you access… #393

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
Copy link
Contributor Author

@raginpirate raginpirate Feb 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I need to fix this, probably requires a bool use_result = false for real nilable result objects.
It should also accept errors that it can hand over to the tag proc too.

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
Loading