Skip to content

Commit

Permalink
Extract plug
Browse files Browse the repository at this point in the history
  • Loading branch information
chulkilee committed Oct 1, 2020
1 parent 81cf27f commit 2a51076
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 12 deletions.
1 change: 1 addition & 0 deletions .formatter.exs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# Used by "mix format"
[
import_deps: [:plug],
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]
26 changes: 26 additions & 0 deletions lib/telemetry_metrics_prometheus/plug.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
defmodule TelemetryMetricsPrometheus.Plug do
@moduledoc """
Plug to export Prometheus metrics.
"""

@behaviour Plug

import Plug.Conn

@impl Plug
def init(opts) do
opts |> Keyword.put_new(:name, :prometheus_metrics)
end

@impl Plug
def call(conn, opts) do
name = Keyword.fetch!(opts, :name)

metrics = TelemetryMetricsPrometheus.Core.scrape(name)

conn
|> put_private(:prometheus_metrics_name, name)
|> put_resp_content_type("text/plain")
|> send_resp(200, metrics)
end
end
17 changes: 5 additions & 12 deletions lib/telemetry_metrics_prometheus/router.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,16 @@ defmodule TelemetryMetricsPrometheus.Router do
@moduledoc false

use Plug.Router
alias Plug.Conn

plug(:match)
plug(Plug.Telemetry, event_prefix: [:prometheus_metrics, :plug])
plug(:dispatch, builder_opts())
plug :match
plug Plug.Telemetry, event_prefix: [:prometheus_metrics, :plug]
plug :dispatch, builder_opts()

get "/metrics" do
name = opts[:name]
metrics = TelemetryMetricsPrometheus.Core.scrape(name)

conn
|> Conn.put_private(:prometheus_metrics_name, name)
|> Conn.put_resp_content_type("text/plain")
|> Conn.send_resp(200, metrics)
TelemetryMetricsPrometheus.Plug.call(conn, opts)
end

match _ do
Conn.send_resp(conn, 404, "Not Found")
send_resp(conn, 404, "Not Found")
end
end

0 comments on commit 2a51076

Please sign in to comment.