logging

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package logging provides a context-aware slog handler that automatically extracts request-scoped attributes from the context and appends them to every log record. This gives all log lines within an HTTP request a shared correlation ID without callers needing to pass it explicitly.

Two layers of context are supported:

  1. ContextAttrs — set once by the logging middleware with the request ID.
  2. Extractors — optional functions registered at init time that pull additional fields (user_id, tenant_id) from context. This avoids an import dependency from logging → auth while still enriching every log line with identity information set by later middleware.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithAttrs

func WithAttrs(ctx context.Context, attrs ContextAttrs) context.Context

WithAttrs stores request-scoped logging attributes in the context.

Types

type ContextAttrs

type ContextAttrs struct {
	RequestID string
}

ContextAttrs are the request-scoped attributes injected by the logging middleware and automatically attached to every slog record.

func AttrsFromContext

func AttrsFromContext(ctx context.Context) ContextAttrs

AttrsFromContext retrieves the request-scoped logging attributes, or returns a zero value if none are set.

type ContextHandler

type ContextHandler struct {
	// contains filtered or unexported fields
}

ContextHandler wraps an slog.Handler and enriches every log record with request-scoped attributes from the context.

func NewContextHandler

func NewContextHandler(inner slog.Handler, extractors ...Extractor) *ContextHandler

NewContextHandler creates a new ContextHandler wrapping the given handler. Optional extractors are called on every log record to pull additional attributes from context (e.g. user_id, tenant_id from auth middleware).

func (*ContextHandler) Enabled

func (h *ContextHandler) Enabled(ctx context.Context, level slog.Level) bool

func (*ContextHandler) Handle

func (h *ContextHandler) Handle(ctx context.Context, record slog.Record) error

func (*ContextHandler) WithAttrs

func (h *ContextHandler) WithAttrs(attrs []slog.Attr) slog.Handler

func (*ContextHandler) WithGroup

func (h *ContextHandler) WithGroup(name string) slog.Handler

type Extractor

type Extractor struct {
	Key     string
	Extract func(ctx context.Context) string
}

Extractor pulls a named attribute value from the context. Registered extractors are called on every log record to enrich it with dynamic context values (e.g. user_id set by auth middleware after the logging middleware has already run).

Jump to

Keyboard shortcuts

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