Introducing a new way to review your PRs.

Read the announcement

basecamp / kamal-proxy

Lightweight proxy server for Kamal

View on GitHub

15 documents · Updated Nov 18, 2026

docs / request-logging

Request logging

Request logging gives the proxy one structured operational record for each handled request. The record joins request identity, connection details, routing context, response results, and timing so an operator can trace traffic through the proxy and relate it to service behavior. See the parent page Proxy observability, and compare this signal with Proxy metrics.

Logging lifecycle

The logging middleware wraps the main proxy handler. It starts a timer before dispatch, lets the handler finish, then writes one INFO record named Request with the final response state and request context. This means the log describes the completed exchange rather than only the incoming request.

The server places request ID middleware outside the logging middleware. An incoming X-Request-ID is kept; a missing value gets a new UUID before the request reaches the logger. The request start middleware also adds an X-Request-Start value for downstream use, but the request log uses its own elapsed duration measurement.

flowchart LR
    A[Incoming request] --> B[Request start]
    B --> C[Request ID]
    C --> D[Logging middleware]
    D --> E[Router and service]
    E --> F[Response completes]
    F --> G[Request log]

Completion record

The completion record is emitted after the wrapped handler returns. The response writer records the status and bytes sent while preserving normal HTTP response behavior, so the log can show the result even when the handler does not call WriteHeader explicitly. Protocol upgrades are recorded as a switching-protocols response when the connection is handed over.

References: internal/…/logging_middleware.go• L53-117 internal/…/logging_middleware.go• L129-173

Lifecycle fields

Each Request record uses stable field names so operators can filter requests and compare them across services. Empty values are possible when a request does not pass through a service or target, or when the client does not send a related header.

Field groupFieldsOperational meaning
Identityrequest_id, method, path, queryFinds one request and describes its HTTP operation.
Listener and protocolhost, port, scheme, protoShows which public endpoint and protocol handled the request.
Result and timingstatus, durationShows the final HTTP status and elapsed time in nanoseconds.
Request bodyreq_content_length, req_content_typeDescribes the request payload known to the proxy.
Response bodyresp_content_length, resp_content_typeDescribes the response written through the proxy.
Client detailsclient_addr, client_port, remote_addr, user_agentIdentifies the connected peer, forwarded client address, and user agent.
Routing contextservice, target, rolloutConnects the request to the selected service, upstream target, and rollout path.

The remote_addr field uses X-Forwarded-For when present. A service can configure a trusted client-IP header that replaces that value before logging. This lets deployments preserve the real client address when another proxy sits in front of the server.

Request and response headers

Services can ask the target path to add selected headers to the request record. Request headers use the req_ prefix and response headers use the resp_ prefix. Header names are lower-cased and converted to underscore form, while repeated values are joined with commas.

This opt-in model keeps the normal record small while allowing service-specific fields such as cache policy or an application header. Header selection is part of target configuration, so changes to that configuration change the available operational fields.

References: internal/…/logging_middleware.go• L83-108 internal/…/logging_middleware.go• L119-127 internal/…/target.go• L174-177

Request context propagation

The logger shares a mutable request context object through the request context. Middleware and routing layers fill in parts of that object as the request moves through the system. The outer logger reads the completed object at the end, which avoids passing logging arguments through every handler interface.

sequenceDiagram
    participant L as Logging middleware
    participant S as Service
    participant T as Target
    participant O as Operational log
    L->>L: Create request context
    L->>S: Pass request with context
    S->>S: Set service and rollout state
    S->>T: Pass request with context
    T->>T: Set target and selected headers
    T-->>L: Return response
    L->>O: Emit completed Request record

Service and target context

The service layer sets service when it handles the request. If rollout selection sends the request to the rollout load balancer, it sets rollout to true. The target layer then sets target and the configured request and response header lists. These values describe the path that actually handled the request.

Metric exclusion context

The same context carries an internal metric-exclusion flag for requests that service options exclude from metrics. The logger still records those requests. Only the metrics tracker skips them, so logs and metrics can have different request counts by design. See Proxy metrics for the related measurement behavior.

References: internal/…/logging_middleware.go• L16-50 internal/…/service.go• L314-322 internal/…/service.go• L527-533 internal/…/service.go• L612-617 internal/…/target.go• L174-183

Middleware boundaries

The request log covers the public HTTP and HTTPS handlers, including HTTP/3 when it uses the shared handler. It does not describe requests sent to the separate metrics listener because that listener has its own handler chain without request logging.

The logger runs outside request body timeout handling and error-page handling. As a result, failures produced by those layers still receive a final status and duration in the request record. The error response content and classification are described in Proxy error responses, while dispatch details are described in Request routing.

Client address boundary

The connected address comes from the transport's remote address. When that value cannot be split into host and port, the full value is kept as client_addr and client_port is empty. The optional client-IP middleware maps a configured header to X-Forwarded-For before the logger resolves remote_addr.

References: internal/…/server.go• L134-180 internal/…/server.go• L183-208 internal/…/server.go• L218-229 internal/…/client_ip_middleware.go• L12-24 internal/…/logging_middleware.go• L65-81

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the request field names aligned with log consumers when changing the structured attributes in internal/…/logging_middleware.go.
  • Keep middleware order aligned with field ownership when changing Server.buildHandler; request IDs and client address overrides must exist before the logger records the request.
  • When changing service or target selection, check that service, target, rollout, and selected header fields still describe the path that handled the request.
  • When changing response-writer behavior, check that status, byte count, flushing, and connection upgrades remain visible to the completion record.

Important failure modes

TriggerConsequenceGuard
A handler returns without writing a response body or statusThe record reports the default status and zero response bytesThe logging response writer starts with 200 and counts every successful write.
A client-IP header is trusted without the correct front-proxy boundaryremote_addr can identify the supplied header value instead of the network peerConfigure the client-IP middleware only for a header controlled by a trusted proxy.
A service or target bypasses the shared request contextservice, target, rollout, or custom header fields can be empty or staleSet context values on the request that reaches the next handler.
The metrics listener is mistaken for a logged proxy listenerMetrics endpoint traffic has no Request recordTreat the metrics listener as a separate operational endpoint.

Key files

FileWhy to read it
internal/…/logging_middleware.goDefines the request record, timing, response capture, client address fields, and custom header fields.
internal/…/server.goShows where logging, request IDs, timeouts, and error responses sit in the public handler chain.
internal/…/request_id_middleware.goDefines preservation and generation of X-Request-ID.
internal/…/client_ip_middleware.goDefines the optional mapping from a trusted client-IP header to the logged remote address.
internal/…/service.goShows how service, rollout, and metric-exclusion context enters the request.
internal/…/target.goShows how the selected upstream target and configured header fields enter the request.
internal/…/logging_middleware_test.goDemonstrates the structured record contract and client address behavior.