Hello, 
I’d be interested in various examples of basic monitoring in the context of a handler on a web server built with Bandit and Plug.
Basically, I’m building a mini blog as a side project to learn Elixir, and I’m wondering how I could add a functionality that times how long it took from the reception of a request by the server until the response is sent, and logs it.
I currently just have the following super basic handler:
get "/" do
conn
|> put_resp_content_type("text/html")
|> send_file(200, "index.html")
end
how do I measure and log execution time for it?
A few ideas/hints to help you find your way:
You can write a Plug (module or function) that stores the initial time when it receives the conn, and then “schedules” code to run before the response is sent to compute the elapsed time.
Note that measuring time until after the response is sent would account also for time that depends on the client (how fast can they consume the response you send).
The duration can be computed using the difference between two readings of the monotonic clock.
The initial time can be stored in a closure or in conn.private.
Happy learning!
Isn’t Bandit exposing that information via Telemetry event? I thought it is there already, you just need to attach yourself and do with that information whatever you need.
thanks for the replies guys 
I’m not sure how to access the Telemetery event, but I’ll look into it, and I’ve been looking at the other doc sources linked, thanks for sharing them 
edit:
Here’s what I have for now, is this good?
get "/" do
start_time = System.monotonic_time(:millisecond)
conn = put_private(conn, :get_index_start_time, start_time)
name = "World"
html = EEx.eval_file("index.html", assigns: [name: name])
conn
|> register_before_send(fn conn ->
end_time = System.monotonic_time(:millisecond)
duration = end_time - conn.private[:get_index_start_time]
Logger.info("GET / completed in #{duration}ms")
conn
end)
|> put_resp_content_type("text/html")
|> send_resp(200, html)
end
This is very similar to what Plug.Logger — Plug v1.18.1 does, so good job!
2 Likes
awesome, thanks for taking the time to let me know I’m on the right path 