Current section

Files

Jump to
retort lib retort server generic logger.ex
Raw

lib/retort/server/generic/logger.ex

defmodule Retort.Server.Generic.Logger do
@moduledoc """
Logs general request information for `Retort.Server.Generic`, similar to what
[`Plug.Logger`](https://hexdocs.pm/plug/Plug.Logger.html) does for `Plug`.
"""
alias Retort.Server.Generic.RPC
require Logger
# Functions
@doc """
Logs the duration of the `Retort.Server.Generic.RPC` as recorded by
`Retort.Server.Generic.RPC.time`.
"""
@spec call(RPC.t()) :: RPC.t()
def call(
rpc = %RPC{
timing: %{
ending_monotonic_time: ending_monotonic_time,
starting_monotonic_time: starting_monotonic_time
}
}
) do
Logger.info(fn ->
diff = time_diff(starting_monotonic_time, ending_monotonic_time)
["Processed request in ", formatted_diff(diff)]
end)
rpc
end
## Private Functions
# See https://github.com/elixir-lang/plug/blob/v1.1.5/lib/plug/logger.ex#L54-L55
defp formatted_diff(diff) when diff > 1000 do
[
diff
|> div(1000)
|> Integer.to_string(),
"ms"
]
end
defp formatted_diff(diff), do: [Integer.to_string(diff), "µs"]
# See https://github.com/elixir-lang/plug/blob/v1.1.5/lib/plug/logger.ex#L48
defp time_diff(start, stop) do
native_diff = stop - start
:erlang.convert_time_unit(native_diff, :native, :micro_seconds)
end
end