logger

package
v0.0.0-...-c7901e9 Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2026 License: MIT Imports: 21 Imported by: 0

README

logger

import "github.com/altessa-s/go-atlas/transport/http/server/middlewares/logger"

Package logger provides HTTP middleware for structured request/response logging. Logs method, path, status code, duration, and client IP for each request. Supports configurable path filtering to exclude health-check and metrics endpoints from log output. Integrates with the realip middleware for accurate client IP logging when behind proxies or load balancers.

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

View Source
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

View Source
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.

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.

View Source
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

func InternedStatusString(code int) string

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

func Middleware(logHandler LogHandler, opt ...Option) func(next http.Handler) http.Handler

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

type BodyRedactFunc func(body string) string

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

type LogHandlerFunc func(ctx context.Context, msg string, statusCode int, fields slogx.Fields)

LogHandlerFunc is a function adapter that implements LogHandler.

func (LogHandlerFunc) Log

func (f LogHandlerFunc) Log(ctx context.Context, msg string, statusCode int, fields slogx.Fields)

Log 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

func WithContextLogger(v *slog.Logger) Option

WithContextLogger sets the contextLogger option.

func WithIgnoreMethods

func WithIgnoreMethods(v ...string) Option

WithIgnoreMethods sets the ignoreMethods option.

func WithIgnorePaths

func WithIgnorePaths(v ...string) Option

WithIgnorePaths sets the ignorePaths option.

func WithIgnorePatterns

func WithIgnorePatterns(v ...*regexp.Regexp) Option

WithIgnorePatterns sets the ignorePatterns option.

func WithIgnoreResponseCodes

func WithIgnoreResponseCodes(v ...int) Option

WithIgnoreResponseCodes sets the ignoreResponseCodes option.

func WithLogRequest

func WithLogRequest() Option

WithLogRequest enables the logRequest option.

func WithLogResponse

func WithLogResponse() Option

WithLogResponse enables the logResponse option.

func WithLogResponseCodes

func WithLogResponseCodes(v ...int) Option

WithLogResponseCodes sets the logResponseCodes option.

func WithTimeFormat

func WithTimeFormat(v timeformat.Format) Option

WithTimeFormat sets the timeFormat option.

Jump to

Keyboard shortcuts

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