Skip to content

Commit 885c731

Browse files
committed
Properly format HTTP request latency for GCL
1 parent a27b61d commit 885c731

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

lib/logger_json/formatters/google_cloud.ex

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -226,13 +226,14 @@ defmodule LoggerJSON.Formatters.GoogleCloud do
226226
defp format_crash_report_location(_meta), do: nil
227227

228228
if Code.ensure_loaded?(Plug.Conn) do
229-
defp format_http_request(%{conn: %Plug.Conn{} = conn}) do
229+
defp format_http_request(%{conn: %Plug.Conn{} = conn} = assigns) do
230230
request_method = conn.method |> to_string() |> String.upcase()
231231
request_url = Plug.Conn.request_url(conn)
232232
status = conn.status
233233
user_agent = LoggerJSON.Formatter.Plug.get_header(conn, "user-agent")
234234
remote_ip = LoggerJSON.Formatter.Plug.remote_ip(conn)
235235
referer = LoggerJSON.Formatter.Plug.get_header(conn, "referer")
236+
latency = http_request_latency(assigns)
236237

237238
json_map(
238239
protocol: Plug.Conn.get_http_protocol(conn),
@@ -241,13 +242,23 @@ defmodule LoggerJSON.Formatters.GoogleCloud do
241242
status: status,
242243
userAgent: user_agent,
243244
remoteIp: remote_ip,
244-
referer: referer
245+
referer: referer,
246+
latency: latency
245247
)
246248
end
247249
end
248250

249251
defp format_http_request(_meta), do: nil
250252

253+
defp http_request_latency(%{duration_us: duration_us}) do
254+
duration_s = Float.round(duration_us / 1_000_000, 9)
255+
"#{duration_s}s"
256+
end
257+
258+
defp http_request_latency(_assigns) do
259+
nil
260+
end
261+
251262
defp format_affected_user(%{user_id: user_id}), do: "user:" <> user_id
252263
defp format_affected_user(%{identity_id: identity_id}), do: "identity:" <> identity_id
253264
defp format_affected_user(%{actor_id: actor_id}), do: "actor:" <> actor_id

test/logger_json/formatters/google_cloud_test.exs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -331,7 +331,7 @@ defmodule LoggerJSON.Formatters.GoogleCloudTest do
331331

332332
log_entry =
333333
capture_log(fn ->
334-
Logger.debug("Hello")
334+
Logger.debug("Hello", duration_us: 123_456)
335335
end)
336336
|> decode_or_print_error()
337337

@@ -342,7 +342,8 @@ defmodule LoggerJSON.Formatters.GoogleCloudTest do
342342
"requestMethod" => "GET",
343343
"requestUrl" => "http://www.example.com/",
344344
"status" => 200,
345-
"userAgent" => "Mozilla/5.0"
345+
"userAgent" => "Mozilla/5.0",
346+
"latency" => "0.123456s"
346347
}
347348
end
348349

@@ -369,7 +370,8 @@ defmodule LoggerJSON.Formatters.GoogleCloudTest do
369370
"requestMethod" => "PATCH",
370371
"requestUrl" => "http://www.example.com/",
371372
"status" => 503,
372-
"userAgent" => "Mozilla/5.0"
373+
"userAgent" => "Mozilla/5.0",
374+
"latency" => nil
373375
}
374376
end
375377

0 commit comments

Comments
 (0)