From b111558f074c53bc5f03b6e91ad1a00c96958ead Mon Sep 17 00:00:00 2001 From: Claudio Ortolina Date: Tue, 4 Mar 2025 20:21:15 +0000 Subject: [PATCH] Use a plug for Prometheus metrics The plug is injected as early as possible in order to respond quickly, without polluting logs. --- .../controllers/metrics_controller.ex | 7 ------ lib/music_library_web/endpoint.ex | 2 ++ lib/music_library_web/router.ex | 4 ---- lib/music_library_web/telemetry/plug.ex | 22 +++++++++++++++++++ 4 files changed, 24 insertions(+), 11 deletions(-) delete mode 100644 lib/music_library_web/controllers/metrics_controller.ex create mode 100644 lib/music_library_web/telemetry/plug.ex diff --git a/lib/music_library_web/controllers/metrics_controller.ex b/lib/music_library_web/controllers/metrics_controller.ex deleted file mode 100644 index 4b68a5bb..00000000 --- a/lib/music_library_web/controllers/metrics_controller.ex +++ /dev/null @@ -1,7 +0,0 @@ -defmodule MusicLibraryWeb.MetricsController do - use MusicLibraryWeb, :controller - - def index(conn, _params) do - send_resp(conn, 200, TelemetryMetricsPrometheus.Core.scrape()) - end -end diff --git a/lib/music_library_web/endpoint.ex b/lib/music_library_web/endpoint.ex index 17ef1de4..ca75e953 100644 --- a/lib/music_library_web/endpoint.ex +++ b/lib/music_library_web/endpoint.ex @@ -15,6 +15,8 @@ defmodule MusicLibraryWeb.Endpoint do encrypt: true ] + plug MusicLibraryWeb.Telemetry.Plug, at: "/metrics" + socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]], longpoll: [connect_info: [session: @session_options]] diff --git a/lib/music_library_web/router.ex b/lib/music_library_web/router.ex index fedd15c6..b078cb9e 100644 --- a/lib/music_library_web/router.ex +++ b/lib/music_library_web/router.ex @@ -69,10 +69,6 @@ defmodule MusicLibraryWeb.Router do use ErrorTracker.Web, :router import Phoenix.LiveDashboard.Router - scope "/metrics", MusicLibraryWeb do - get "/", MetricsController, :index - end - scope "/dev" do pipe_through [:browser, :logged_in] diff --git a/lib/music_library_web/telemetry/plug.ex b/lib/music_library_web/telemetry/plug.ex new file mode 100644 index 00000000..9625eca9 --- /dev/null +++ b/lib/music_library_web/telemetry/plug.ex @@ -0,0 +1,22 @@ +defmodule MusicLibraryWeb.Telemetry.Plug do + @behaviour Plug + + import Plug.Conn + + def init(opts) do + Keyword.validate!(opts, [:at]) + end + + def call(conn, opts) do + at = Keyword.fetch!(opts, :at) + + if conn.request_path == at do + conn + |> put_resp_content_type("text/plain") + |> send_resp(200, TelemetryMetricsPrometheus.Core.scrape()) + |> halt() + else + conn + end + end +end