Documentation
¶
Overview ¶
Package logger provides HTTP middleware for structured request/response logging. It supports configurable filtering and integrates with the realip middleware for accurate client IP logging.
Example with realip middleware:
ipExtractor := clientip.NewExtractor()
router.Use(
realip.Middleware(ipExtractor),
logger.Middleware(logger.Slog(slog.Default())),
)
Example standalone:
mw := logger.Middleware(logger.Slog(slog.Default()),
logger.WithIgnorePaths("/health", "/metrics"),
)
Index ¶
- Constants
- Variables
- func InternedStatusString(code int) string
- func Middleware(logHandler LogHandler, opt ...Option) func(next http.Handler) http.Handler
- func New(logHandler LogHandler, opt ...Option) *middleware
- type BodyRedactFunc
- type LogHandler
- type LogHandlerFunc
- type Option
- func WithBodyRedactor(v BodyRedactFunc) Option
- func WithContextLogger(v *slog.Logger) Option
- func WithIgnoreMethods(v ...string) Option
- func WithIgnorePaths(v ...string) Option
- func WithIgnorePatterns(v ...*regexp.Regexp) Option
- func WithIgnoreResponseCodes(v ...int) Option
- func WithLogRequest() Option
- func WithLogResponse() Option
- func WithLogResponseCodes(v ...int) Option
- func WithTimeFormat(v timeformat.Format) Option
Constants ¶
const ( // DefaultFieldsCapacity is the default capacity for pre-allocated log fields // passed to [LogHandler.Log]. This reduces allocations for typical request // logging scenarios where roughly 15 fields are collected (method, path, // proto, peer_ip, user_agent, real_ip, status, start_time, end_time, // duration, request_id, and optional request/response content). DefaultFieldsCapacity = 15 )
Variables ¶
var ( FieldKeyHTTPMethod loggerfields.FieldKey = corestrings.InternString("http.method") FieldKeyHTTPPath loggerfields.FieldKey = corestrings.InternString("http.path") FieldKeyHTTPProto loggerfields.FieldKey = corestrings.InternString("http.proto") FieldKeyHTTPStatus loggerfields.FieldKey = corestrings.InternString("http.status") )
HTTP-specific field keys used by the logger Middleware. Interned via strings.InternString for memory efficiency, since these strings appear in every logged request entry.
var DefaultLogStatusCodes = []int{ http.StatusOK, http.StatusCreated, http.StatusAccepted, http.StatusNoContent, http.StatusMovedPermanently, http.StatusFound, http.StatusNotModified, http.StatusBadRequest, http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound, http.StatusMethodNotAllowed, http.StatusConflict, http.StatusGone, http.StatusUnprocessableEntity, http.StatusTooManyRequests, http.StatusInternalServerError, http.StatusNotImplemented, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout, }
DefaultLogStatusCodes contains common HTTP status codes that should be logged by default. Used by New when no custom WithLogResponseCodes option is provided. Pre-allocated at initialization to avoid per-request allocation.
var DefaultLogStatusCodesSet = func() map[int]struct{} { m := make(map[int]struct{}, len(DefaultLogStatusCodes)) for _, code := range DefaultLogStatusCodes { m[code] = struct{}{} } return m }()
DefaultLogStatusCodesSet is a pre-computed set for O(1) lookup of DefaultLogStatusCodes. Used by the middleware's shouldLogStatusCode hot path.
Functions ¶
func InternedStatusString ¶
InternedStatusString returns the interned string representation of an HTTP status code. Common codes are pre-computed at init time; unknown codes are interned on first use via strings.InternString.
func Middleware ¶
Middleware defines a middleware that logs HTTP requests with configurable options. It uses the LogHandler interface for flexibility, allowing different logging backends.
This is a convenience function; prefer New() for access to the full Middleware interface. For slog.Logger, use: logger.Middleware(logger.Slog(myLogger), opts...)
Example usage:
// Using LogHandler interface
middleware := logger.Middleware(logger.Slog(myLogger),
logger.WithTimeFormat(logger.TimeFormatUnixMilli),
)
// Production mode
middleware := logger.Middleware(logger.Slog(myLogger),
logger.WithIgnoreResponseCodes(200, 204, 304),
logger.WithIgnorePaths("/health", "/ready"),
logger.WithIgnoreMethods("OPTIONS", "HEAD"),
)
func New ¶
func New(logHandler LogHandler, opt ...Option) *middleware
New creates a new logger middleware with the given LogHandler and options. If logHandler is nil, the returned middleware is a no-op pass-through.
This is the recommended way to create the logger middleware. For slog.Logger, use: logger.New(logger.Slog(myLogger), opts...)
Types ¶
type BodyRedactFunc ¶
BodyRedactFunc is called to redact sensitive data from request/response body content before it is written to logs. It receives the raw body string and must return the redacted version. Applied only when WithLogRequest or WithLogResponse is enabled. Configure with WithBodyRedactor.
type LogHandler ¶
type LogHandler interface {
Log(ctx context.Context, msg string, statusCode int, fields slogx.Fields)
}
LogHandler is the logging backend interface for the logger middleware. Implementations receive the request context, a message, the HTTP status code, and structured fields collected during request processing. The built-in adapter Slog wraps a slog.Logger; implement this interface for custom logging backends. Pass instances to New or Middleware.
func Slog ¶
func Slog(l *slog.Logger) LogHandler
Slog creates a LogHandler backed by a slog.Logger for use with New or Middleware. The log level is derived from the HTTP status code: 5xx and 401/403 produce Error, 4xx produce Warn, and all others produce Info. Fields are converted to slog attributes with dot-notation grouping.
type LogHandlerFunc ¶
LogHandlerFunc is a function adapter that implements LogHandler.
type Option ¶
type Option func(o *options)
Option is a functional option for configuring options.
func WithBodyRedactor ¶
func WithBodyRedactor(v BodyRedactFunc) Option
WithBodyRedactor sets the bodyRedactor option.
func WithContextLogger ¶
WithContextLogger sets the contextLogger option.
func WithIgnoreMethods ¶
WithIgnoreMethods sets the ignoreMethods option.
func WithIgnorePaths ¶
WithIgnorePaths sets the ignorePaths option.
func WithIgnorePatterns ¶
WithIgnorePatterns sets the ignorePatterns option.
func WithIgnoreResponseCodes ¶
WithIgnoreResponseCodes sets the ignoreResponseCodes option.
func WithLogResponse ¶
func WithLogResponse() Option
WithLogResponse enables the logResponse option.
func WithLogResponseCodes ¶
WithLogResponseCodes sets the logResponseCodes option.
func WithTimeFormat ¶
func WithTimeFormat(v timeformat.Format) Option
WithTimeFormat sets the timeFormat option.