Created
August 8, 2022 13:54
-
-
Save s3cur3/8a5fe8fc99eaa34dac985d98b3e60e78 to your computer and use it in GitHub Desktop.
A telemetry handler to log slow events on your Phoenix Channel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule AppServerWeb.Telemetry do | |
require Logger | |
@doc """ | |
Attaches an event handler to the "handled in" event on your Phoenix Channels. | |
Call from within your application.ex initialization. | |
""" | |
def attach_telemetry_handlers() do | |
channel_handled_in = [:phoenix, :channel_handled_in] | |
:telemetry.attach( | |
{__MODULE__, channel_handled_in}, | |
channel_handled_in, | |
&__MODULE__.log_slow_handled_in/4, | |
:ok | |
) | |
end | |
def log_slow_handled_in(_, %{duration: duration}, %{socket: socket} = metadata, _) do | |
duration_ms = System.convert_time_unit(duration, :native, :millisecond) | |
max_duration_ms = 500 | |
if duration_ms > max_duration_ms do | |
%{event: event, params: params} = metadata | |
duration_sec = System.convert_time_unit(duration, :native, :second) | |
details = %{ | |
channel: socket.channel, | |
params: params | |
} | |
Logger.info( | |
"Slow channel event #{event} on #{socket.topic} " <> | |
"(#{duration_sec} seconds): #{inspect(details)}" | |
) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment