Skip to content

Commit 3d98834

Browse files
authored
chore(add-user-agent-in-logs): Add User-Agent header to ECS logs (#47)
1 parent a10742b commit 3d98834

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

neurow/lib/neurow/ecs_log_formatter.ex

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ defmodule Neurow.EcsLogFormatter do
3939
|> with_optional_attribute(metadata[:error_code], "error.code")
4040
|> with_optional_attribute(metadata[:client_ip], "client.ip")
4141
|> with_optional_attribute(metadata[:authorization_header], "http.request.authorization")
42+
|> with_optional_attribute(metadata[:user_agent_header], "user_agent.original")
4243
|> :jiffy.encode()
4344
|> newline()
4445
end

neurow/lib/neurow/jwt_auth_plug.ex

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,7 @@ defmodule Neurow.JwtAuthPlug do
225225
category: "security",
226226
error_code: "jwt_authentication.#{error_code}",
227227
authorization_header: conn |> get_req_header("authorization") |> List.first(),
228+
user_agent_header: conn |> get_req_header("user-agent") |> List.first(),
228229
trace_id: conn |> get_req_header("x-request-id") |> List.first(),
229230
client_ip: conn |> get_req_header("x-forwarded-for") |> List.first()
230231
)

neurow/test/neurow/ecs_log_formatter_test.exs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,40 @@ defmodule Neurow.EcsLogFormatterTest do
101101
}
102102
end
103103

104+
test "supports optional user_agent_header metadata" do
105+
metadata = %{
106+
time: 1_728_556_213_722_376,
107+
mfa: {Neurow.EcsLogFormatterTest, :fake_function, 4},
108+
file: "test/neurow/ecs_log_formatter_test.exs",
109+
line: 10,
110+
user_agent_header: "Mozilla/5.0"
111+
}
112+
113+
json_log =
114+
Neurow.EcsLogFormatter.format(:info, "Hello, world!", nil, metadata)
115+
|> :jiffy.decode([:return_maps])
116+
117+
assert json_log == %{
118+
"@timestamp" => "2024-10-10T10:30:13.722376Z",
119+
"log.level" => "info",
120+
"log.name" => "Elixir.Neurow.EcsLogFormatterTest.fake_function/4",
121+
"log.source" => %{
122+
"file" => %{
123+
"name" => "test/neurow/ecs_log_formatter_test.exs",
124+
"line" => 10
125+
}
126+
},
127+
"ecs.version" => "8.11.0",
128+
"message" => "Hello, world!",
129+
"category" => "app",
130+
"service" => %{
131+
"name" => "neurow",
132+
"version" => "unknown"
133+
},
134+
"user_agent.original" => "Mozilla/5.0"
135+
}
136+
end
137+
104138
test "supports optional client_ip metadata" do
105139
metadata = %{
106140
time: 1_728_556_213_722_376,

0 commit comments

Comments
 (0)