stripe / stripe-ruby

Ruby library for the Stripe API.
https://stripe.com
MIT License
1.96k stars 548 forks source link

Example of using instrumentation in code #1467

Closed rlgreen91 closed 3 weeks ago

rlgreen91 commented 1 month ago

Is your feature request related to a problem? Please describe.

How exactly do I use the instrumentation option in my code? I see the information in the docs noting the feature and with an example of what the configuration for the instrumentation might be, but where do I actually place this in my code? It doesn't appear to be a configuration option.

Describe the solution you'd like

A full example of where to place the instrumentation code relative to using the gem.

Describe alternatives you've considered

No response

Additional context

No response

prathmesh-stripe commented 1 month ago

Place it before you make a call to Stripe API. As long as Stripe module is accessible from your script and you can make API calls to Stripe, this would work.

Stripe::Instrumentation.subscribe(:request_end) do |request_event|
  # Filter out high-cardinality ids from `path`
  path_parts = request_event.path.split("/").drop(2)
  resource = path_parts.map { |part| part.match?(/\A[a-z_]+\z/) ? part : ":id" }.join("/")

  tags = {
    method: request_event.method,
    resource: resource,
    code: request_event.http_status,
    retries: request_event.num_retries
  }
  StatsD.distribution('stripe_request', request_event.duration, tags: tags)
end

Stripe-ruby will invoke whatever is in the block when a request starts or ends depending on the hook you've subscribed to.

rlgreen91 commented 1 month ago

Thanks @prathmesh-stripe ! To clarify, would I need to list this block before every API call? Or could I put this in say, an initializer file in Rails and it will automatically execute the block for every API call?

helenye-stripe commented 4 weeks ago

You should be able to define a block and pass it in once in the beginning, where it will subscribe you until you call Stripe::Instrumentation.unsubscribe:

Stripe::Instrumentation.subscribe(:request_begin, :sub) { |event| puts "Began #{event.method} #{event.path}" }

Note the second parameter here, which is a name for the subscriber.

helenye-stripe commented 3 weeks ago

Closing as the issue has been addressed. Feel free to re-open or open a new issue if more questions come up!