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

feat(request_id): add custom Logger's metadata option #1247

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
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