Skip to content

Commit

Permalink
Include client ip in ECS logs if the IP is provided in the x-forward-…
Browse files Browse the repository at this point in the history
…ip header
  • Loading branch information
achouippe committed Oct 15, 2024
1 parent 9091464 commit f2985bb
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
1 change: 1 addition & 0 deletions neurow/lib/neurow/ecs_log_formatter.ex
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ defmodule Neurow.EcsLogFormatter do
}
|> with_optional_attribute(metadata[:trace_id], "trace.id")
|> with_optional_attribute(metadata[:error_code], "error.code")
|> with_optional_attribute(metadata[:client_ip], "client.ip")
|> :jiffy.encode()
|> newline()
end
Expand Down
3 changes: 2 additions & 1 deletion neurow/lib/neurow/jwt_auth_plug.ex
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,8 @@ defmodule Neurow.JwtAuthPlug do
"JWT authentication error: #{error_code} - #{error_message}, path: '#{conn.request_path}', audience: '#{options |> Options.audience()}', token: '#{jwt_token}'",
category: "security",
error_code: "jwt_authentication.#{error_code}",
trace_id: conn |> get_req_header("x-request-id") |> List.first()
trace_id: conn |> get_req_header("x-request-id") |> List.first(),
client_ip: conn |> get_req_header("x-forwarded-for") |> List.first()
)

conn =
Expand Down
34 changes: 34 additions & 0 deletions neurow/test/neurow/ecs_log_formatter_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,40 @@ defmodule Neurow.EcsLogFormatterTest do
}
end

test "supports optional client_ip metadata" do
metadata = %{
time: 1_728_556_213_722_376,
mfa: {Neurow.EcsLogFormatterTest, :fake_function, 4},
file: "test/neurow/ecs_log_formatter_test.exs",
line: 10,
client_ip: "127.01.02.03"
}

json_log =
Neurow.EcsLogFormatter.format(:info, "Hello, world!", nil, metadata)
|> :jiffy.decode([:return_maps])

assert json_log == %{
"@timestamp" => "2024-10-10T10:30:13.722376Z",
"log.level" => "info",
"log.name" => "Elixir.Neurow.EcsLogFormatterTest.fake_function/4",
"log.source" => %{
"file" => %{
"name" => "test/neurow/ecs_log_formatter_test.exs",
"line" => 10
}
},
"ecs.version" => "8.11.0",
"message" => "Hello, world!",
"category" => "app",
"service" => %{
"name" => "neurow",
"version" => "unknown"
},
"client.ip" => "127.01.02.03"
}
end

test "multiline messages are inlined" do
metadata = %{
time: 1_728_556_213_722_376,
Expand Down

0 comments on commit f2985bb

Please sign in to comment.