Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
13 changes: 10 additions & 3 deletions lib/plug/request_id.ex
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ defmodule Plug.RequestId do

plug Plug.RequestId, assign_as: :plug_request_id

* `:log_as` - The name of the key that will be used to store the
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would name this :logger_metadata_key.

discovered or generated request id in `Logger` metadata. If not provided,
the request id will be stored as `:request_id`.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
the request id will be stored as `:request_id`.
the request ID Logger metadata key defaults to `:request_id`.


plug Plug.RequestId, log_as: :my_request_id
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
plug Plug.RequestId, log_as: :my_request_id
plug Plug.RequestId, log_as: :my_request_id
*Available since v1.18.0*.


"""

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

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

Logger.metadata(request_id: request_id)
Logger.metadata([{log_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 @@ -82,6 +82,20 @@ defmodule Plug.RequestIdTest do
assert res_request_id == meta_request_id
end

test "adds the request id to Logger metadata with the given log key" do
request_id = "existingidthatislongenough"

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

[res_request_id] = get_resp_header(conn, "x-request-id")
meta_request_id = Logger.metadata()[:plug_request_id]
assert generated_request_id?(res_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