Skip to content

Commit

Permalink
feat(request_id): add custom Logger's metadata option
Browse files Browse the repository at this point in the history
  • Loading branch information
georgeguimaraes committed Sep 23, 2024
1 parent e11e5c4 commit 7877999
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
14 changes: 11 additions & 3 deletions lib/plug/request_id.ex
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ defmodule Plug.RequestId do
config :logger, :default_formatter, metadata: [:request_id]
We recommend to include this metadata configuration in your production
configuration file.
configuration file. You can also configure a custom metadata key using
`:metadata_as` (see below).
> #### Programmatic access to the request ID {: .tip}
>
Expand All @@ -47,6 +48,12 @@ defmodule Plug.RequestId do
plug Plug.RequestId, assign_as: :plug_request_id
* `:metadata_as` - The key to use when storing the request ID in Logger metadata.
Default value is `:request_id`.
plug Plug.RequestId, metadata_as: :correlation_id
"""

require Logger
Expand All @@ -57,15 +64,16 @@ defmodule Plug.RequestId do
def init(opts) do
{
Keyword.get(opts, :http_header, "x-request-id"),
Keyword.get(opts, :metadata_as, :request_id),
Keyword.get(opts, :assign_as)
}
end

@impl true
def call(conn, {header, assign_as}) do
def call(conn, {header, metadata_as, assign_as}) do
request_id = get_request_id(conn, header)

Logger.metadata(request_id: request_id)
Logger.metadata([{metadata_as, request_id}])
conn = if assign_as, do: Conn.assign(conn, assign_as, request_id), else: conn

Conn.put_resp_header(conn, header, request_id)
Expand Down
14 changes: 14 additions & 0 deletions test/plug/request_id_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,20 @@ defmodule Plug.RequestIdTest do
assert res_request_id == meta_request_id
end

test "uses the custom Logger metadata if it was given" do
request_id = "existingidthatislongenough"

conn =
conn(:get, "/")
|> put_req_header("x-request-id", request_id)
|> call(metadata_as: :correlation_id)

[res_request_id] = get_resp_header(conn, "x-request-id")
meta_request_id = Logger.metadata()[:correlation_id]
assert res_request_id == request_id
assert res_request_id == meta_request_id
end

defp generated_request_id?(request_id) do
Regex.match?(~r/\A[A-Za-z0-9-_]+\z/, request_id)
end
Expand Down

0 comments on commit 7877999

Please sign in to comment.