httplog

package
v0.15.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package httplog writes the access log of an HTTP server: one record per request, through the application's own *slog.Logger, so access lines share its output, level, trace correlation and sinks.

Usage

Put RequestLogger into the group of business routes, after middleware.Trace, so a record carries the trace of the request and its route:

r.Use(
    middleware.Trace(middleware.TraceConfig{TracerProvider: d.TracerProvider}),
    httplog.RequestLogger(d.Logger.With("logger", "access"), &httplog.Options{
        Level:         slog.LevelInfo,
        Schema:        httplog.SchemaOTEL.Concise(true),
        RecoverPanics: true,
    }),
    d.Metrics.Middleware(),
)

A handler adds its own attributes to the record with SetAttrs and its error with SetError.

Fields

The record's level follows the status code: 5xx — error, 4xx — warn (429 — info), OPTIONS — debug, the rest — info. Its message is the method, the path without the query, the status code and the duration: "GET /v1/widgets/42 => HTTP 200 (1.2ms)". The query stays out: it may carry tokens and personal data.

The fields are named by the Schema; with SchemaOTEL, the default, they are the names of the OpenTelemetry semantic conventions, so the access log, the server span and the HTTP metrics share one vocabulary and one value:

  • http.request.method — middleware.Method: a standard method, else _OTHER;
  • http.route — middleware.Route, e.g. /v1/widgets/{id}; absent outside a route;
  • http.response.status_code;
  • http.server.request.duration — in seconds;
  • client.address — the first X-Forwarded-For hop, else the host of the connection's address, without the port.

Concise keeps these, the error and the headers and bodies the Options log; the full schema adds the URL, host, scheme, protocol, sizes, user agent and referer.

Errors

An error goes under ErrorKey ("err") as an error value, the key of every log record of the service: SetError's, ErrClientAborted when the client went away (with error.type ClientAborted), and a recovered panic as "panic: <value>" with its stack under exception.stacktrace.

Options

  • Level: the lowest level recorded (default info).
  • Schema: SchemaOTEL (default), SchemaECS or SchemaGCP; Concise(true) for the essential fields only.
  • RecoverPanics: turn a panic into a 500 (default on).
  • Skip: a predicate to leave a request out.
  • LogRequestHeaders, LogResponseHeaders: the headers to record (default Content-Type and Origin, and Content-Type).
  • LogRequestBody, LogResponseBody, LogBodyContentTypes, LogBodyMaxLen: the bodies to record, their content types and length (default 1024 bytes).
  • LogExtraAttrs: more attributes from the request, its body and status.

Index

Constants

View Source
const (
	ECSResponseDuration  = "event.duration"
	OTELResponseDuration = "http.server.request.duration"
	GCPResponseDuration  = "httpRequest:latency"
)
View Source
const ErrorKey = "err"

ErrorKey is the key of the error of a request log; its value is the error itself, as in every log record of the service.

Variables

View Source
var (
	// SchemaECS represents the Elastic Common Schema (ECS) version 9.0.0.
	// This schema is widely used with Elasticsearch and the Elastic Stack.
	//
	// Reference: https://www.elastic.co/guide/en/ecs/current/ecs-http.html
	SchemaECS = &Schema{
		Timestamp:          "@timestamp",
		Level:              "log.level",
		Message:            "message",
		ErrorMessage:       "error.message",
		ErrorType:          "error.type",
		ErrorStackTrace:    "error.stack_trace",
		SourceFile:         "log.origin.file.name",
		SourceLine:         "log.origin.file.line",
		SourceFunction:     "log.origin.function",
		RequestURL:         "url.full",
		RequestMethod:      "http.request.method",
		RequestPath:        "url.path",
		RequestRemoteIP:    "client.ip",
		RequestHost:        "url.domain",
		RequestScheme:      "url.scheme",
		RequestProto:       "http.version",
		RequestHeaders:     "http.request.headers",
		RequestBody:        "http.request.body.content",
		RequestBytes:       "http.request.body.bytes",
		RequestBytesUnread: "http.request.body.unread.bytes",
		RequestUserAgent:   "user_agent.original",
		RequestReferer:     "http.request.referrer",
		ResponseHeaders:    "http.response.headers",
		ResponseBody:       "http.response.body.content",
		ResponseStatus:     "http.response.status_code",
		ResponseDuration:   ECSResponseDuration,
		ResponseBytes:      "http.response.body.bytes",
	}

	// SchemaOTEL represents OpenTelemetry (OTEL) semantic conventions version 1.34.0.
	// This schema follows OpenTelemetry standards for observability data.
	//
	// Reference: https://opentelemetry.io/docs/specs/semconv/http/http-metrics
	SchemaOTEL = &Schema{
		Timestamp:          "timestamp",
		Level:              "severity_text",
		Message:            "body",
		ErrorMessage:       "error.message",
		ErrorType:          "error.type",
		ErrorStackTrace:    "exception.stacktrace",
		SourceFile:         "code.filepath",
		SourceLine:         "code.lineno",
		SourceFunction:     "code.function",
		RequestURL:         "url.full",
		RequestMethod:      "http.request.method",
		RequestPath:        "url.path",
		RequestRoute:       "http.route",
		RequestRemoteIP:    "client.address",
		RequestHost:        "server.address",
		RequestScheme:      "url.scheme",
		RequestProto:       "network.protocol.version",
		RequestHeaders:     "http.request.header",
		RequestBody:        "http.request.body.content",
		RequestBytes:       "http.request.body.size",
		RequestBytesUnread: "http.request.body.unread.size",
		RequestUserAgent:   "user_agent.original",
		RequestReferer:     "http.request.header.referer",
		ResponseHeaders:    "http.response.header",
		ResponseBody:       "http.response.body.content",
		ResponseStatus:     "http.response.status_code",
		ResponseDuration:   OTELResponseDuration,
		ResponseBytes:      "http.response.body.size",
	}

	// SchemaGCP represents Google Cloud Platform's structured logging format.
	// This schema is optimized for Google Cloud Logging service.
	//
	// References:
	//   - https://cloud.google.com/logging/docs/structured-logging
	//   - https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#HttpRequest
	SchemaGCP = &Schema{
		Timestamp:          "timestamp",
		Level:              "severity",
		Message:            "message",
		ErrorMessage:       "error",
		ErrorType:          "error_type",
		ErrorStackTrace:    "stack_trace",
		SourceFile:         "logging.googleapis.com/sourceLocation:file",
		SourceLine:         "logging.googleapis.com/sourceLocation:line",
		SourceFunction:     "logging.googleapis.com/sourceLocation:function",
		RequestURL:         "httpRequest:requestUrl",
		RequestMethod:      "httpRequest:requestMethod",
		RequestPath:        "httpRequest:requestPath",
		RequestRemoteIP:    "httpRequest:remoteIp",
		RequestHost:        "httpRequest:host",
		RequestScheme:      "httpRequest:scheme",
		RequestProto:       "httpRequest:protocol",
		RequestHeaders:     "httpRequest:requestHeaders",
		RequestBody:        "httpRequest:requestBody",
		RequestBytes:       "httpRequest:requestSize",
		RequestBytesUnread: "httpRequest:requestUnreadSize",
		RequestUserAgent:   "httpRequest:userAgent",
		RequestReferer:     "httpRequest:referer",
		ResponseHeaders:    "httpRequest:responseHeaders",
		ResponseBody:       "httpRequest:responseBody",
		ResponseStatus:     "httpRequest:status",
		ResponseDuration:   GCPResponseDuration,
		ResponseBytes:      "httpRequest:responseSize",
		GroupDelimiter:     ":",
	}
)
View Source
var ErrClientAborted = fmt.Errorf("request aborted: client disconnected before response was sent")

Functions

func CURL

func CURL(req *http.Request, reqBody string) string

CURL returns a curl command for the given request and body.

func RequestLogger

func RequestLogger(logger *slog.Logger, o *Options) func(http.Handler) http.Handler

RequestLogger builds the request-logging middleware. It writes through the given logger's handler, so HTTP access logs share the output, level, trace correlation and sinks of the rest of the application — one handler, distinct instances. Pass a dedicated child, e.g. log.With("logger", "access"), to tag access lines. A nil Options falls back to the package defaults.

The method (middleware.Method), route (middleware.Route), status code and client address are the values the server span and the HTTP metrics record, under the names of the Schema (SchemaOTEL by default). The message leaves the query out: it may carry tokens and personal data. An error — SetError, a client that went away, a panic — goes under ErrorKey as an error value.

func SetAttrs

func SetAttrs(ctx context.Context, attrs ...slog.Attr)

SetAttrs sets the attributes on the request log.

func SetError

func SetError(ctx context.Context, err error) error

SetError sets the error attribute on the request log.

Types

type Options

type Options struct {
	// Level defines the verbosity of the request logs:
	// slog.LevelDebug - log both request starts & responses (incl. OPTIONS)
	// slog.LevelInfo  - log responses (excl. OPTIONS)
	// slog.LevelWarn  - log 4xx and 5xx responses only (except for 429)
	// slog.LevelError - log 5xx responses only
	//
	// You can override the level with a custom slog.Handler (e.g. on per-request basis).
	Level slog.Level

	// Schema defines the mapping of semantic log fields to their corresponding
	// field names in different logging systems and standards.
	//
	// This enables log output in different formats compatible with various logging
	// platforms and standards (ECS, OTEL, GCP, etc.) by providing the schema.
	//
	// httplog.SchemaOTEL (OpenTelemetry, the default)
	// httplog.SchemaECS (Elastic Common Schema)
	// httplog.SchemaGCP (Google Cloud Platform)
	//
	// Append .Concise(true) to reduce log verbosity (e.g. for localhost development).
	Schema *Schema

	// RecoverPanics recovers from panics occurring in the underlying HTTP handlers
	// and middlewares and returns HTTP 500 unless response status was already set.
	//
	// NOTE: Panics are logged as errors automatically, regardless of this setting.
	RecoverPanics bool

	// Skip is an optional predicate function that determines whether to skip
	// recording logs for a given request.
	//
	// If nil, all requests are recorded.
	// If provided, requests where Skip returns true will not be recorded.
	Skip func(req *http.Request, respStatus int) bool

	// LogRequestHeaders is a list of headers to be logged as attributes.
	// If not provided, the default is ["Content-Type", "Origin"].
	//
	// WARNING: Do not leak any request headers with sensitive information.
	LogRequestHeaders []string

	// LogRequestBody is an optional predicate function that controls logging of request body.
	//
	// If the function returns true, the request body will be logged.
	// If false, no request body will be logged.
	//
	// WARNING: Do not leak any request bodies with sensitive information.
	LogRequestBody func(req *http.Request) bool

	// LogResponseHeaders controls a list of headers to be logged as attributes.
	//
	// If not provided, there are no default headers.
	LogResponseHeaders []string

	// LogRequestBody is an optional predicate function that controls logging of request body.
	//
	// If the function returns true, the request body will be logged.
	// If false, no request body will be logged.
	//
	// WARNING: Do not leak any response bodies with sensitive information.
	LogResponseBody func(req *http.Request) bool

	// LogBodyContentTypes defines a list of body Content-Types that are safe to be logged
	// with LogRequestBody or LogResponseBody options.
	//
	// If not provided, the default is ["application/json", "application/xml", "text/plain", "text/csv", "application/x-www-form-urlencoded", ""].
	LogBodyContentTypes []string

	// LogBodyMaxLen defines the maximum length of the body to be logged.
	//
	// If not provided, the default is 1024 bytes. Set to -1 to log the full body.
	LogBodyMaxLen int

	// LogExtraAttrs is an optional function that lets you add extra attributes to the
	// request log.
	//
	// Example:
	//
	// // Log all requests with invalid payload as curl command.
	// func(req *http.Request, reqBody string, respStatus int) []slog.Attr {
	//     if respStatus == 400 || respStatus == 422 {
	// 	       req.Header.Del("Authorization")
	//         return []slog.Attr{slog.String("curl", httplog.CURL(req, reqBody))}
	// 	   }
	// 	   return nil
	// }
	//
	// WARNING: Be careful not to leak any sensitive information in the logs.
	LogExtraAttrs func(req *http.Request, reqBody string, respStatus int) []slog.Attr
}

type Schema

type Schema struct {
	// Base attributes for core logging information.
	Timestamp       string // Timestamp of the log entry
	Level           string // Log level (e.g. INFO, WARNING, ERROR)
	Message         string // Primary log message
	ErrorMessage    string // Error message when an error occurs
	ErrorType       string // Low-cardinality error type (e.g. "ClientAborted", "ValidationError")
	ErrorStackTrace string // Stack trace for panic or error

	// Source code location attributes for tracking origin of log statements.
	SourceFile     string // Source file name where the log originated
	SourceLine     string // Line number in the source file
	SourceFunction string // Function name where the log originated

	// Request attributes for the incoming HTTP request.
	// NOTE: RequestQuery is intentionally not supported as it would likely leak sensitive data.
	RequestURL         string // Full request URL
	RequestMethod      string // HTTP method (e.g. GET, POST)
	RequestPath        string // URL path component
	RequestRoute       string // Route template (e.g. /v1/widgets/{id})
	RequestRemoteIP    string // Client IP address
	RequestHost        string // Host header value
	RequestScheme      string // URL scheme (http, https)
	RequestProto       string // HTTP protocol version (e.g. HTTP/1.1, HTTP/2)
	RequestHeaders     string // Selected request headers
	RequestBody        string // Request body content, if logged.
	RequestBytes       string // Size of request body in bytes
	RequestBytesUnread string // Unread bytes in request body
	RequestUserAgent   string // User-Agent header value
	RequestReferer     string // Referer header value

	// Response attributes for the HTTP response.
	ResponseHeaders  string // Selected response headers
	ResponseBody     string // Response body content, if logged.
	ResponseStatus   string // HTTP status code
	ResponseDuration string // Request processing duration
	ResponseBytes    string // Size of response body in bytes

	// GroupDelimiter is an optional delimiter for nested objects in some formats.
	// For example, GCP uses nested JSON objects like "httpRequest": {}.
	GroupDelimiter string
}

Schema defines the mapping of semantic log fields to their corresponding field names in different logging systems and standards.

This enables log output in different formats compatible with various logging platforms and standards (ECS, OTEL, GCP, etc.) by providing the schema.

func (*Schema) Concise

func (s *Schema) Concise(concise bool) *Schema

Concise returns a simplified schema with essential fields only: the method, route, status code and duration of the request, the client address, the error, and the headers and bodies the Options log. If concise is false, it returns s.

func (*Schema) ReplaceAttr

func (s *Schema) ReplaceAttr(groups []string, a slog.Attr) slog.Attr

ReplaceAttr returns transforms standard slog attribute names to the schema format.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL