Skip to content

Instantly share code, notes, and snippets.

@s3cur3
Created August 8, 2022 13:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s3cur3/8a5fe8fc99eaa34dac985d98b3e60e78 to your computer and use it in GitHub Desktop.
Save s3cur3/8a5fe8fc99eaa34dac985d98b3e60e78 to your computer and use it in GitHub Desktop.
A telemetry handler to log slow events on your Phoenix Channel
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