|
1 | 1 | defmodule Unplug do
|
2 | 2 | @moduledoc """
|
3 |
| - Documentation for `Unplug`. |
4 |
| - """ |
| 3 | + This plug acts as a filter for Plug.Telemetry and allows you to filter out |
| 4 | + events based on the incoming URL. |
| 5 | +
|
| 6 | + When servicing requests, Phoenix will log information about the incoming |
| 7 | + request and outgoing response. In some cases it may pollute the logs |
| 8 | + if certain endpoints are triggered and logged at regular intervals (for |
| 9 | + example logging for `/metrics` when using something like Prometheus to |
| 10 | + collect metrics or `/health` if you are health checking your application |
| 11 | + with Kubernetes). |
5 | 12 |
|
6 |
| - @doc """ |
7 |
| - Hello world. |
| 13 | + To use this in your application, open up your `endpoint.ex` file and replace: |
| 14 | + `plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]` |
8 | 15 |
|
9 |
| - ## Examples |
| 16 | + with |
10 | 17 |
|
11 |
| - iex> Unplug.hello() |
12 |
| - :world |
| 18 | + `plug TelemetryFilter, filter_endpoints: ["/metrics", "/health"], event_prefix: [:phoenix, :endpoint]` |
13 | 19 |
|
| 20 | + Feel free to replace the values for `:filter_endpoints` with whatever endpoints |
| 21 | + you would like to omit telemetry events for. |
14 | 22 | """
|
15 |
| - def hello do |
16 |
| - :world |
| 23 | + |
| 24 | + @behaviour Plug |
| 25 | + |
| 26 | + plug(Unplug, run_plug: Plug.Telemetry, run_plug_opts: [], eval: {Unplug}, eval_opts: []) |
| 27 | + |
| 28 | + @impl true |
| 29 | + def init(opts) do |
| 30 | + plug_telemetry_opts = Telemetry.init(opts) |
| 31 | + telemetry_filter_opts = Keyword.get(opts, :filter_endpoints, []) |
| 32 | + |
| 33 | + {plug_telemetry_opts, telemetry_filter_opts} |
| 34 | + end |
| 35 | + |
| 36 | + @impl true |
| 37 | + def call(conn, {plug_telemetry_opts, []}) do |
| 38 | + Telemetry.call(conn, plug_telemetry_opts) |
| 39 | + end |
| 40 | + |
| 41 | + def call(conn, {plug_telemetry_opts, telemetry_filter_opts}) do |
| 42 | + if Enum.member?(telemetry_filter_opts, conn.request_path) do |
| 43 | + conn |
| 44 | + else |
| 45 | + Telemetry.call(conn, plug_telemetry_opts) |
| 46 | + end |
17 | 47 | end
|
18 | 48 | end
|
0 commit comments