~ihabunek/triglav

113d8b3efc45ee9c074561def800674a558df56f — Ivan Habunek 4 months ago ec69d6f
Add slow query log
2 files changed, 34 insertions(+), 0 deletions(-)

M lib/triglav/application.ex
A lib/triglav/telemetry.ex
M lib/triglav/application.ex => lib/triglav/application.ex +2 -0
@@ 19,6 19,8 @@ defmodule Triglav.Application do
        ]
      end

    Triglav.Telemetry.start!()

    opts = [strategy: :one_for_one, name: Triglav.Supervisor]
    Supervisor.start_link(children, opts)
  end

A lib/triglav/telemetry.ex => lib/triglav/telemetry.ex +32 -0
@@ 0,0 1,32 @@
defmodule Triglav.Telemetry do
  require Logger

  @slow_query_threshold_ms 500

  def start! do
    :ok = :telemetry.attach("triglav", [:triglav, :repo, :query], &Triglav.Telemetry.handle_event/4, %{})
  end

  def handle_event([:triglav, :repo, :query], measurements, metadata, _config) do
    if ms(measurements.total_time) > @slow_query_threshold_ms do
      timings = measurements
      |> Map.take([:total_time, :query_time, :idle_time])
      |> Map.new(fn {k, v} -> {k, ms(v)} end)

      log_message = """
      SLOW QUERY ( > #{@slow_query_threshold_ms}ms ) #{inspect(timings)}
        query: #{metadata[:query]}
        params: #{inspect(metadata[:params])}
      """

      Logger.warning(log_message)
    end
  end

  def handle_event(_, _, _, _) do
    :ok
  end

  defp ms(nil), do: nil
  defp ms(native), do: :erlang.convert_time_unit(native, :native, :millisecond)
end