Sinatra - How to calculate response time for each request for statistics purposes?

I would like to measure the runtime of each Sinatra route, including the total length of the request / response cycle, and then send these metrics to the Graphite server.

My first approach was to use Rack::Runtimeand then extract the values ​​that I need from the response headers in Sinatra after, but I found that this filter is actually executed before the response is completely sent to the client.

Thus, I cannot access many response messages in a block after, I also can not use this block to send Graphite indicators in any other way, because they will not reflect the real response time.

I read in other topics that a possible approach is to create Rack middleware to port the application and run the test, and I ended up with something like this:

class GraphiteRoutesReporter

  def initialize(app)
    @app = app
  end

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

    # send #{time_taken} to my stats server

    [status, headers, body]
  end
end

What can I include in config.ruand it seems to be working fine.

But I'm worried about this running the code with the main Rack request chain, and I'm worried I'm misusing the open Sinatra API.

What is the correct way to get the full response time of a Sinatra request?

+4
source share
1 answer

-- ( "" -), "" (awk) log output of sinatra, ( : 0.1093 - )

179.24.226.1 - felixb [22/Aug/2016:13:30:46 +0200] "GET /index HTTP/1.0" 200 11546 0.1093

Logger, , (, ).

, , , # send #{time_taken} to my stats server - , , , .

, -/, https://github.com/MiniProfiler/rack-mini-profiler.

0

Source: https://habr.com/ru/post/1651657/


All Articles