lib/salestation/web/statsd_middleware.rb in salestation-3.4.0 vs lib/salestation/web/statsd_middleware.rb in salestation-3.5.0

- old
+ new

@@ -1,19 +1,22 @@ # frozen_string_literal: true module Salestation class Web < Module class StatsdMiddleware + EXTRA_TAGS_ENV_KEY = 'salestation.statsd.tags' + DURATION_PRECISION = 6 + def initialize(app, statsd, metric:) @app = app @statsd = statsd @metric = metric end def call(env) - start = Time.now + start = system_monotonic_time status, header, body = @app.call env method = env['REQUEST_METHOD'] path = @@ -21,16 +24,28 @@ route.split(' ').last else 'unknown-route' end - @statsd.timing(@metric, (Time.now - start) * 1000, tags: [ + tags = [ "path:#{ path }", "method:#{ method }", "status:#{ status }" - ]) + ] + env.fetch(EXTRA_TAGS_ENV_KEY, []) + @statsd.timing(@metric, duration(from: start), tags: tags) + [status, header, body] + end + + private + + def duration(from:) + (system_monotonic_time - from).round(DURATION_PRECISION) + end + + def system_monotonic_time + Process.clock_gettime(Process::CLOCK_MONOTONIC) end end end end