Skip to content

Commit 67faa57

Browse files
authored
Customize the Logger metadata key name (#1267)
In certain scenarios we may want to use the Plug.RequestID multiple times with different configuration options (maybe different headers or different assigns). While this is possible, the issue is that every call adds a `:request_id` key to the Logger metadata. When using the plug muliple times, the last call will override the metadata of the previous one. This commit adds a new `:logger_metadata_key` option that allows users to customize how the request ID will be added to the logger metadata. If not provided, this option defaults to `:request_id` for backwards compatibility.
1 parent 88f79c2 commit 67faa57

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

lib/plug/request_id.ex

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,13 @@ defmodule Plug.RequestId do
4747
4848
plug Plug.RequestId, assign_as: :plug_request_id
4949
50+
* `:logger_metadata_key` - The name of the key that will be used to store the
51+
discovered or generated request id in `Logger` metadata. If not provided,
52+
the request ID Logger metadata will be stored as `:request_id`. *Available
53+
since v1.18.0*.
54+
55+
plug Plug.RequestId, logger_metadata_key: :my_request_id
56+
5057
"""
5158

5259
require Logger
@@ -57,15 +64,16 @@ defmodule Plug.RequestId do
5764
def init(opts) do
5865
{
5966
Keyword.get(opts, :http_header, "x-request-id"),
60-
Keyword.get(opts, :assign_as)
67+
Keyword.get(opts, :assign_as),
68+
Keyword.get(opts, :logger_metadata_key, :request_id)
6169
}
6270
end
6371

6472
@impl true
65-
def call(conn, {header, assign_as}) do
73+
def call(conn, {header, assign_as, logger_metadata_key}) do
6674
request_id = get_request_id(conn, header)
6775

68-
Logger.metadata(request_id: request_id)
76+
Logger.metadata([{logger_metadata_key, request_id}])
6977
conn = if assign_as, do: Conn.assign(conn, assign_as, request_id), else: conn
7078

7179
Conn.put_resp_header(conn, header, request_id)

test/plug/request_id_test.exs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,20 @@ defmodule Plug.RequestIdTest do
8282
assert res_request_id == meta_request_id
8383
end
8484

85+
test "adds the request id to Logger metadata with the given log key" do
86+
request_id = "existingidthatislongenough"
87+
88+
conn =
89+
conn(:get, "/")
90+
|> put_req_header("x-request-id", request_id)
91+
|> call(logger_metadata_key: :plug_request_id)
92+
93+
[res_request_id] = get_resp_header(conn, "x-request-id")
94+
meta_request_id = Logger.metadata()[:plug_request_id]
95+
assert generated_request_id?(res_request_id)
96+
assert res_request_id == meta_request_id
97+
end
98+
8599
defp generated_request_id?(request_id) do
86100
Regex.match?(~r/\A[A-Za-z0-9-_]+\z/, request_id)
87101
end

0 commit comments

Comments
 (0)