Plug v1.8.0 Plug.Telemetry View Source
A plug to instrument the pipeline with :telemetry
events.
When plugged, the event prefix is a required option:
plug Plug.Telemetry, event_prefix: [:my, :plug]
In the example above, two events will be emitted:
[:my, :plug, :start]
- emitted when the plug is invoked. The event carries a single measurement,:time
, which is the system time in native units at the moment the event is emitted. The only metadata is the wholePlug.Conn
under the:conn
key.[:my, :plug, :stop]
- emitted right before the request is sent. The event carries a single measurement,:duration
, which is the monotonic time difference between the stop and start events. The same as for the start event, the only metadata is thePlug.Conn
struct under the:conn
key.
After the Plug is added, please be sure to add :telemetry as project dependency.
Note that this plug measures only the time between its invocation and the rest of the plug pipeline - this can be used to exclude some plugs from measurement.
Time unit
Both :time
and :duration
measurements are presented in the :native
time unit. You can read more about it in the docs for System.convert_time_unit/3
.
Example
defmodule InstrumentedPlug do
use Plug.Router
plug :match
plug Plug.Telemetry, event_prefix: [:my, :plug]
plug Plug.Parsers, parsers: [:urlencoded, :multipart]
plug :dispatch
get "/" do
send_resp(conn, 200, "Hello, world!")
end
end
In this example, the stop event's duration
includes the time
it takes to parse the request, dispatch it to the correct handler,
and execute the handler. The events are not emitted for requests
not matching any handlers, since the plug is placed after the match plug.