fix(14.2-03): access log records a cancelled request's 5xx as 499

A client that goes away mid-request cancels the context; a handler then
fails on context.Canceled and writes a 500 nobody receives. The request
log now records it as 499 (client closed request) so a grep for 5xx shows
real server errors only.
This commit is contained in:
2026-10-11 20:27:56 +02:00
parent 66dbd5a64a
commit 4660f95e5c
4 changed files with 51 additions and 3 deletions

View File

@@ -2,6 +2,7 @@ package surf
import (
"context"
"errors"
"log/slog"
"net/http"
"time"
@@ -25,6 +26,11 @@ type accessEntry struct {
type accessEntryKey struct{}
// statusClientClosedRequest is nginx's 499 "client closed request": the
// status the access log records for a request whose client went away before
// the handler answered.
const statusClientClosedRequest = 499
// accessLogEnabled reports whether http.access_log is true.
func accessLogEnabled(app *backpack.App) bool {
return app != nil && app.Config != nil && app.Config.Bool(accessLogKey)
@@ -36,7 +42,10 @@ func accessLogEnabled(app *backpack.App) bool {
// (a ServeMux 404 or 405, or a CORS preflight answered before routing) is
// path added, set to the URL path without the query string. The query
// string, headers, the remote address and a matched route's raw path are
// never logged: share and invitation tokens travel in paths. The logger is
// never logged: share and invitation tokens travel in paths. A 5xx written
// after the client cancelled the request (its context ends with
// context.Canceled) is logged as 499: the error came from the cancellation,
// and no client received it. The logger is
// the app's published *slog.Logger, else slog.Default (which the generated
// main wraps in the redacting sunscreen handler).
func accessLog(app *backpack.App, next http.Handler) http.Handler {
@@ -49,6 +58,9 @@ func accessLog(app *backpack.App, next http.Handler) http.Handler {
if status == 0 {
status = http.StatusOK
}
if status >= http.StatusInternalServerError && errors.Is(req.Context().Err(), context.Canceled) {
status = statusClientClosedRequest
}
attrs := []slog.Attr{
slog.String("method", req.Method),
slog.String("pattern", entry.pattern),