Created
June 18, 2021 12:49
-
-
Save nwalker/662045870b3433d9cdeec5d8e11e47fe to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Laundry.Logger do | |
require Logger | |
def install() do | |
%{ | |
[:phoenix, :router_dispatch, :stop] => &__MODULE__.request_finish/4, | |
} |> Enum.each(fn {key, handler} -> | |
:telemetry.detach({__MODULE__, key}) | |
:telemetry.attach({__MODULE__, key}, key, handler, :ok) | |
end) | |
end | |
# def request_finish(_, _, %{log: false}, _), do: :ok | |
def request_finish(_, %{duration: duration}, %{conn: conn} = metadata, _) do | |
Logger.info( | |
log_msg_fun(conn, duration), | |
log_meta(metadata) | |
) | |
rescue | |
any -> IO.inspect(any, label: "RESCUE") | |
catch | |
any -> IO.inspect(any, label: "CATCH") | |
end | |
def log_msg_fun(c, duration) do | |
fn () -> | |
[ | |
c.method, | |
?\s, c.request_path, | |
if(map_size(c.query_params) > 0, do: [?\s, "qs:", inspect(c.query_params)]) || [], | |
if(map_size(c.body_params) > 0, do: [?\s, "body:", inspect(c.body_params)]) || [], | |
" -> ", inspect(c.status), " in ", duration(duration) | |
] | |
end | |
end | |
def log_meta(%{conn: c, } = meta) do | |
[ | |
remote_ip: ip(c.remote_ip), | |
] ++ get_phoenix_handler(meta) | |
end | |
def get_phoenix_handler(meta) do | |
[handler: case meta do | |
%{plug_opts: action} when is_atom(action) -> [inspect(meta.plug), ?., Atom.to_string(meta.plug_opts), ?/, ?2] | |
_ -> inspect(meta.plug) | |
end |> IO.chardata_to_string] | |
rescue | |
any -> | |
IO.inspect any, label: "HCATCH" | |
[] | |
end | |
def ip({a, b, c, d}) do | |
"#{to_string(a)}.#{to_string(b)}.#{to_string(c)}.#{to_string(d)}" | |
end | |
def ip(other), do: inspect(other) | |
def duration(duration) do | |
duration = System.convert_time_unit(duration, :native, :microsecond) | |
if duration > 1000 do | |
[duration |> div(1000) |> Integer.to_string(), "ms"] | |
else | |
[Integer.to_string(duration), "µs"] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment