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 ¶
A nil Options takes the defaults below. A non-nil one is taken as it is: only LogBodyContentTypes and LogBodyMaxLen fall back to theirs, and a nil Schema to SchemaOTEL.
- Level: the lowest level recorded (info).
- Schema: SchemaOTEL, SchemaECS or SchemaGCP; Concise(true) for the essential fields only.
- RecoverPanics: turn a panic into a 500 (on).
- Skip: a predicate to leave a request out.
- LogRequestHeaders, LogResponseHeaders: the headers to record (Content-Type and Origin, and Content-Type).
- LogRequestBody, LogResponseBody, LogBodyContentTypes, LogBodyMaxLen: the bodies to record, their content types and length (1024 bytes).
- LogExtraAttrs: more attributes from the request, its body and status; CURL turns the request into a curl command.
Schema.ReplaceAttr, as the ReplaceAttr of the slog handler of the service, renames the base fields of every record — time, level, message, source — to the names of the schema, so the other records share them with the access log.
Example ¶
RequestLogger writes one record per request through the logger of the service. A handler adds its attributes with SetAttrs and its error with SetError; the status sets the level.
package main
import (
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"strings"
"github.com/assanoff/skit/httplog"
"github.com/assanoff/skit/rest/router"
)
// stable drops what changes from run to run, the time and the duration, so
// the example prints the same record every time.
func stable(groups []string, a slog.Attr) slog.Attr {
if len(groups) > 0 {
return a
}
switch a.Key {
case slog.TimeKey, httplog.OTELResponseDuration:
return slog.Attr{}
case slog.MessageKey:
msg, _, _ := strings.Cut(a.Value.String(), " (")
return slog.String(a.Key, msg)
}
return a
}
func main() {
log := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: stable}))
access := httplog.RequestLogger(log, &httplog.Options{
Schema: httplog.SchemaOTEL.Concise(true),
RecoverPanics: true,
})
r := router.New()
api := r.With(access) // the group of business routes, after middleware.Trace
api.HandleFunc("GET /widgets/{id}", func(w http.ResponseWriter, r *http.Request) {
httplog.SetAttrs(r.Context(), slog.String("widget.id", r.PathValue("id")))
w.WriteHeader(http.StatusOK)
})
api.HandleFunc("GET /report", func(w http.ResponseWriter, r *http.Request) {
err := httplog.SetError(r.Context(), errors.New("clickhouse: timeout"))
http.Error(w, err.Error(), http.StatusServiceUnavailable)
})
for _, path := range []string{"/widgets/42?token=secret", "/report"} {
r.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, path, nil))
}
}
Output: {"level":"INFO","msg":"GET /widgets/42 => HTTP 200","http.request.method":"GET","client.address":"192.0.2.1","http.response.status_code":200,"http.route":"/widgets/{id}","widget.id":"42"} {"level":"ERROR","msg":"GET /report => HTTP 503","http.request.method":"GET","client.address":"192.0.2.1","http.response.status_code":503,"http.route":"/report","err":"clickhouse: timeout"}
Index ¶
Examples ¶
Constants ¶
const ( ECSResponseDuration = "event.duration" OTELResponseDuration = "http.server.request.duration" GCPResponseDuration = "httpRequest:latency" )
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 ¶
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: ":", } )
var ErrClientAborted = fmt.Errorf("request aborted: client disconnected before response was sent")
Functions ¶
func CURL ¶
CURL returns a curl command for the given request and body. A body of any method goes in --data-raw; -X names the method when curl would send another one: GET without a body, POST with one.
Example ¶
CURL turns a request into a curl command, e.g. in LogExtraAttrs to replay a request the server rejected.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/assanoff/skit/httplog"
)
func main() {
req := httptest.NewRequest(http.MethodPost, "/v1/widgets", nil)
req.Header.Set("Content-Type", "application/json")
fmt.Println(httplog.CURL(req, `{"name":"gadget"}`))
}
Output: curl 'http://example.com/v1/widgets' --data-raw '{"name":"gadget"}' -H 'Content-Type: application/json'
func RequestLogger ¶
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.
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 ¶
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 ¶
ReplaceAttr renames the base slog attributes — time, level, message, source — to the names of the schema; pass it as the ReplaceAttr of slog.HandlerOptions.
Example ¶
ReplaceAttr renames the base fields of every record of the service, not only the access log, to the names of a schema, here ECS.
package main
import (
"context"
"log/slog"
"os"
"github.com/assanoff/skit/httplog"
)
func main() {
ecs := func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{} // a stable output
}
return httplog.SchemaECS.ReplaceAttr(groups, a)
}
log := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: ecs}))
log.InfoContext(context.Background(), "server started", "port", 8080)
}
Output: {"log.level":"INFO","message":"server started","port":8080}