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

fix(elastic): encode duration_μs inserted by LoggerJSON.Plug as event.duration #129

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion lib/logger_json/formatters/elastic.ex
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,8 @@ defmodule LoggerJSON.Formatters.Elastic do
# - http.*: https://www.elastic.co/guide/en/ecs/8.11/ecs-http.html
# - url.path: https://www.elastic.co/guide/en/ecs/8.11/ecs-url.html
# - user_agent.original: https://www.elastic.co/guide/en/ecs/8.11/ecs-user_agent.html
defp format_http_request(%{conn: %Plug.Conn{} = conn}) do
# - event.duration (note: ns, not μs): https://www.elastic.co/guide/en/ecs/current/ecs-event.html#field-event-duration
defp format_http_request(%{conn: %Plug.Conn{} = conn, duration_μs: duration_μs}) do
%{
"client.ip": LoggerJSON.Formatter.Plug.remote_ip(conn),
"http.version": Plug.Conn.get_http_protocol(conn),
Expand All @@ -270,7 +271,10 @@ defmodule LoggerJSON.Formatters.Elastic do
"url.path": conn.request_path,
"user_agent.original": LoggerJSON.Formatter.Plug.get_header(conn, "user-agent")
}
|> maybe_put(:"event.duration", to_nanosecs(duration_μs))
end

defp format_http_request(%{conn: %Plug.Conn{} = conn}), do: format_http_request(%{conn: conn, duration_μs: nil})
end

defp format_http_request(_meta), do: nil
Expand All @@ -288,4 +292,7 @@ defmodule LoggerJSON.Formatters.Elastic do
end

defp safe_chardata_to_string(other), do: other

defp to_nanosecs(duration) when is_number(duration), do: duration * 1000
defp to_nanosecs(_), do: nil
end
3 changes: 2 additions & 1 deletion test/logger_json/formatters/elastic_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ defmodule LoggerJSON.Formatters.ElasticTest do
|> Plug.Conn.put_req_header("x-forwarded-for", "")
|> Plug.Conn.send_resp(200, "Hi!")

Logger.metadata(conn: conn)
Logger.metadata(conn: conn, duration_μs: 1337)

log_entry =
capture_log(fn ->
Expand All @@ -378,6 +378,7 @@ defmodule LoggerJSON.Formatters.ElasticTest do

assert %{
"client.ip" => "",
"event.duration" => 1_337_000,
"http.version" => "HTTP/1.1",
"http.request.method" => "GET",
"http.request.referrer" => "http://www.example2.com/",
Expand Down
Loading