Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Monotonic time for calculating request latency in Plug.Logger #373

Merged
merged 2 commits into from
Mar 30, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should use :erlang.monotonic_time(:micro_seconds) here and remove convert_time_unit call.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's not do that because we lose precision. The ideal is to always convert later.

defp time_diff(start, stop), do: (stop - start) |> :erlang.convert_time_unit(:native, :micro_seconds)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we remove the piping here?

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