Skip to content
Browse files

add middleware for instrumentation with Active Support

  • Loading branch information...
1 parent 4e3047a commit 23d5e614eea4f48dd5a0eee68eb8b3d5e65b5275 @mislav mislav committed
Showing with 35 additions and 1 deletion.
  1. +5 −1 lib/faraday_middleware.rb
  2. +30 −0 lib/faraday_middleware/instrumentation.rb
View
6 lib/faraday_middleware.rb
@@ -14,7 +14,8 @@ class << self
:ParseYaml => 'response/parse_yaml',
:Caching => 'response/caching',
:RackCompatible => 'rack_compatible',
- :FollowRedirects => 'response/follow_redirects'
+ :FollowRedirects => 'response/follow_redirects',
+ :Instrumentation => 'instrumentation'
}
# autoload without the autoload
@@ -45,6 +46,9 @@ class << self
:yaml => lambda { ParseYaml },
:caching => lambda { Caching },
:follow_redirects => lambda { FollowRedirects }
+
+ Faraday.register_middleware \
+ :instrumentation => lambda { Instrumentation }
end
end
View
30 lib/faraday_middleware/instrumentation.rb
@@ -0,0 +1,30 @@
+require 'faraday'
+
+module FaradayMiddleware
+ # Public: Instruments requests using Active Support.
+ #
+ # Measures time spent only for synchronous requests.
+ #
+ # Examples
+ #
+ # ActiveSupport::Notifications.subscribe('request.faraday') do |name, start_time, end_time, _, env|
+ # url = env[:url]
+ # http_method = env[:method].to_s.upcase
+ # duration = end_time - start_time
+ # $stderr.puts '[%s] %s %s (%.3f s)' % [url.host, http_method, url.request_uri, duration]
+ # end
+ class Instrumentation < Faraday::Middleware
+ dependency 'active_support/notifications'
+
+ def initialize(app, options = {})
+ super(app)
+ @name = options.fetch(:name, 'request.faraday')
+ end
+
+ def call(env)
+ ActiveSupport::Notifications.instrument(@name, env) do
+ @app.call(env)
+ end
+ end
+ end
+end

0 comments on commit 23d5e61

Please sign in to comment.
Something went wrong with that request. Please try again.