Skip to content

Commit

Permalink
Merge pull request #373 from mje113/monotonic
Browse files Browse the repository at this point in the history
Use Monotonic time for calculating request latency in Plug.Logger
  • Loading branch information
josevalim committed Mar 30, 2016
2 parents c536571 + 3aac991 commit 4f486ae
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions lib/plug/logger.ex
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,29 @@ defmodule Plug.Logger do
[conn.method, ?\s, conn.request_path]
end

before_time = :os.timestamp()
start = current_time()

Conn.register_before_send(conn, fn conn ->
Logger.log level, fn ->
after_time = :os.timestamp()
diff = :timer.now_diff(after_time, before_time)
stop = current_time()
diff = time_diff(start, stop)

[connection_type(conn), ?\s, Integer.to_string(conn.status),
" in ", formatted_diff(diff)]
end
conn
end)
end

# TODO: remove this once Plug supports only Elixir 1.2.
if function_exported?(:erlang, :monotonic_time, 0) do
defp current_time, do: :erlang.monotonic_time
defp time_diff(start, stop), do: (stop - start) |> :erlang.convert_time_unit(:native, :micro_seconds)
else
defp current_time, do: :os.timestamp()
defp time_diff(start, stop), do: :timer.now_diff(stop, start)
end

defp formatted_diff(diff) when diff > 1000, do: [diff |> div(1000) |> Integer.to_string, "ms"]
defp formatted_diff(diff), do: [diff |> Integer.to_string, "µs"]

Expand Down

0 comments on commit 4f486ae

Please sign in to comment.