Class: RubyAPI::Middleware::Metrics

Inherits:
Object
  • Object
show all
Defined in:
lib/fastrb/middleware/logging.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Metrics

Returns a new instance of Metrics.



33
34
35
36
37
38
# File 'lib/fastrb/middleware/logging.rb', line 33

def initialize(app)
  @app = app
  @counts = Hash.new(0)
  @latencies = Hash.new(0.0)
  @mutex = Mutex.new
end

Instance Attribute Details

#countsObject (readonly)

Returns the value of attribute counts.



31
32
33
# File 'lib/fastrb/middleware/logging.rb', line 31

def counts
  @counts
end

#latenciesObject (readonly)

Returns the value of attribute latencies.



31
32
33
# File 'lib/fastrb/middleware/logging.rb', line 31

def latencies
  @latencies
end

Instance Method Details

#call(env) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/fastrb/middleware/logging.rb', line 40

def call(env)
  start_time = Time.now
  status, headers, body = @app.call(env)
  duration = Time.now - start_time

  key = "#{env["REQUEST_METHOD"]} #{env["PATH_INFO"]}"
  @mutex.synchronize do
    @counts[key] += 1
    @latencies[key] += duration
  end

  [status, headers, body]
end

#summaryObject



54
55
56
57
58
59
60
61
62
63
64
# File 'lib/fastrb/middleware/logging.rb', line 54

def summary
  @mutex.synchronize do
    @counts.each_with_object({}) do |(key, count), hash|
      total = @latencies[key]
      hash[key] = {
        count: count,
        avg_latency_ms: (total / count * 1000).round(2)
      }
    end
  end
end