Skip to content

Commit

Permalink
feat: allow logger handler to know about HTTP request details (#420)
Browse files Browse the repository at this point in the history
  • Loading branch information
grzuy authored Nov 14, 2024
1 parent 299e47e commit e2cb861
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
16 changes: 10 additions & 6 deletions lib/bandit/pipeline.ex
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@ defmodule Bandit.Pipeline do
{:upgrade, adapter.transport, protocol, opts}
end
rescue
exception -> handle_error(:error, exception, __STACKTRACE__, transport, span, opts)
exception -> handle_error(:error, exception, __STACKTRACE__, transport, span, opts, conn)
catch
:throw, value ->
handle_error(:throw, value, __STACKTRACE__, transport, span, opts)
handle_error(:throw, value, __STACKTRACE__, transport, span, opts, conn)
end
rescue
exception ->
Expand Down Expand Up @@ -202,9 +202,12 @@ defmodule Bandit.Pipeline do
Exception.stacktrace(),
Bandit.HTTPTransport.t(),
Bandit.Telemetry.t(),
map()
map(),
Plug.Conn.t() | nil
) :: {:ok, Bandit.HTTPTransport.t()} | {:error, term()}
defp handle_error(:error, %type{} = error, stacktrace, transport, span, opts)
defp handle_error(kind, error, stacktrace, transport, span, opts, conn \\ nil)

defp handle_error(:error, %type{} = error, stacktrace, transport, span, opts, _conn)
when type in [
Bandit.HTTPError,
Bandit.HTTP2.Errors.StreamError,
Expand All @@ -220,15 +223,16 @@ defmodule Bandit.Pipeline do
{:error, error}
end

defp handle_error(kind, reason, stacktrace, transport, span, opts) do
defp handle_error(kind, reason, stacktrace, transport, span, opts, conn) do
Bandit.Telemetry.span_exception(span, kind, reason, stacktrace)
status = reason |> Plug.Exception.status() |> Plug.Conn.Status.code()

if status in Keyword.get(opts.http, :log_exceptions_with_status_codes, 500..599) do
Logger.error(
Exception.format(kind, reason, stacktrace),
domain: [:bandit],
crash_reason: crash_reason(kind, reason, stacktrace)
crash_reason: crash_reason(kind, reason, stacktrace),
conn: conn
)

Bandit.HTTPTransport.send_on_error(transport, reason)
Expand Down
5 changes: 4 additions & 1 deletion test/bandit/http1/request_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,10 @@ defmodule HTTP1RequestTest do
assert %{
level: :error,
msg: _msg,
meta: %{crash_reason: {%RuntimeError{message: "boom"}, [_ | _] = _stacktrace}}
meta: %{
crash_reason: {%RuntimeError{message: "boom"}, [_ | _] = _stacktrace},
conn: %Plug.Conn{}
}
} = log_event
end

Expand Down

0 comments on commit e2cb861

Please sign in to comment.