Class: StatsdRack::Rack
- Inherits:
-
Object
- Object
- StatsdRack::Rack
- Defined in:
- lib/statsd-rack/rack.rb
Defined Under Namespace
Classes: Body
Constant Summary collapse
- REQUEST_METHOD =
'REQUEST_METHOD'.freeze
- VALID_METHODS =
['GET', 'HEAD', 'POST', 'PUT', 'DELETE'].freeze
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, prefix = nil) ⇒ Rack
constructor
Initializes the middleware.
-
#record_request(status, env) ⇒ Object
called after request is processed.
- #status_suffix(status) ⇒ Object
Constructor Details
#initialize(app, prefix = nil) ⇒ Rack
Initializes the middleware
prefix - String prefix for Statsd key.
Defaults to 'rack'
15 16 17 18 19 20 21 22 |
# File 'lib/statsd-rack/rack.rb', line 15 def initialize(app, prefix=nil) @app = app stats_prefix = prefix || 'rack' @track_gc = GC.respond_to?(:time) if !$statsd $statsd = ::Statsd.new('localhost', 9125).tap{|sd| sd.namespace = stats_prefix} end end |
Instance Method Details
#call(env) ⇒ Object
99 100 101 102 103 104 105 |
# File 'lib/statsd-rack/rack.rb', line 99 def call(env) @start = Time.now GC.clear_stats if @track_gc status, headers, body = @app.call(env) body = Body.new(body) { record_request(status, env) } [status, headers, body] end |
#record_request(status, env) ⇒ Object
called after request is processed.
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/statsd-rack/rack.rb', line 25 def record_request(status, env) now = Time.now diff = (now - @start) if $statsd $statsd.timing("response_time", diff * 1000) if VALID_METHODS.include?(env[REQUEST_METHOD]) stat = "response_time.#{env[REQUEST_METHOD].downcase}" $statsd.timing(stat, diff * 1000) end if suffix = status_suffix(status) $statsd.increment "status_code.#{status_suffix(status)}" end if @track_gc && GC.time > 0 $statsd.timing "gc.time", GC.time / 1000 $statsd.count "gc.collections", GC.collections end end rescue => boom warn "Statsd::Rack#record_request failed: #{boom}" end |
#status_suffix(status) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/statsd-rack/rack.rb', line 49 def status_suffix(status) suffix = case status.to_i when 200 then :ok when 201 then :created when 202 then :accepted when 301 then :moved_permanently when 302 then :found when 303 then :see_other when 304 then :not_modified when 305 then :use_proxy when 307 then :temporary_redirect when 400 then :bad_request when 401 then :unauthorized when 402 then :payment_required when 403 then :forbidden when 404 then :missing when 410 then :gone when 422 then :invalid when 500 then :error when 502 then :bad_gateway when 503 then :node_down when 504 then :gateway_timeout end end |