ctxlog

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2026 License: MIT Imports: 6 Imported by: 0

README

go-ctxlog

CI Go Reference License

Context-aware structured logging helpers for Go's log/slog

Installation

go get github.com/philiprehberger/go-ctxlog

Usage

import "github.com/philiprehberger/go-ctxlog"
Attaching fields to context
ctx := ctxlog.With(ctx, "user_id", 42, "tenant", "acme")
ctx = ctxlog.WithAttrs(ctx, slog.String("service", "api"))
ctx = ctxlog.WithRequestID(ctx, "req-abc-123")
Correlation ID

Attach a correlation ID to group related requests across services:

ctx = ctxlog.WithCorrelationID(ctx, "corr-abc-123")

// Later, extract it
id := ctxlog.CorrelationID(ctx) // "corr-abc-123"

// Automatically included in logger output as "correlation_id"
ctxlog.Logger(ctx).Info("processing order")
Trace ID

Attach a trace ID for distributed tracing:

ctx = ctxlog.WithTraceID(ctx, "trace-xyz-789")

// Later, extract it
id := ctxlog.TraceID(ctx) // "trace-xyz-789"

// Automatically included in logger output as "trace_id"
ctxlog.Logger(ctx).Info("calling downstream service")
Extracting fields

Retrieve all typed slog.Attr values attached via WithAttrs:

ctx = ctxlog.WithAttrs(ctx, slog.String("service", "api"), slog.Int("port", 8080))
attrs := ctxlog.Fields(ctx) // []slog.Attr{slog.String("service", "api"), slog.Int("port", 8080)}
Logging with context fields
// Uses slog.Default() enriched with context fields
ctxlog.Logger(ctx).Info("request handled", "status", 200)

// Enrich a specific logger
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
ctxlog.From(ctx, logger).Error("something failed", "err", err)
HTTP middleware
mux := http.NewServeMux()
mux.HandleFunc("/", handler)

// Auto-generate request IDs
http.ListenAndServe(":8080", ctxlog.Middleware(mux))
// Use an existing header for the request ID
wrapped := ctxlog.MiddlewareWithHeader("X-Trace-ID")(mux)
http.ListenAndServe(":8080", wrapped)
Configurable middleware

Use MiddlewareWithConfig for full control over request ID generation, header names, and request/response logging:

wrapped := ctxlog.MiddlewareWithConfig(ctxlog.MiddlewareConfig{
    HeaderName:   "X-Correlation-ID",        // read ID from this header (default "X-Request-ID")
    GenerateID:   func() string { return myCustomID() }, // custom ID generator
    LogRequests:  true,                       // log incoming requests
    LogResponses: true,                       // log completed responses with status and duration
})(mux)
http.ListenAndServe(":8080", wrapped)

Zero-value fields use sensible defaults (header "X-Request-ID", UUID v4 generator, no logging).

API

Function Description
With(ctx, args...) Attach slog key-value pairs to context
WithAttrs(ctx, attrs...) Attach typed slog.Attr values to context
WithRequestID(ctx, id) Attach a request ID to context
RequestID(ctx) Extract request ID from context (returns "" if not set)
WithCorrelationID(ctx, id) Attach a correlation ID to context
CorrelationID(ctx) Extract correlation ID from context (returns "" if not set)
WithTraceID(ctx, id) Attach a trace ID to context
TraceID(ctx) Extract trace ID from context (returns "" if not set)
Fields(ctx) Extract all typed slog.Attr values from context
Logger(ctx) Returns slog.Default() enriched with all context fields
From(ctx, logger) Enrich a specific *slog.Logger with context fields
Middleware(next) HTTP middleware that generates a UUID v4 request ID
MiddlewareWithHeader(header) Middleware that reads request ID from a header, or generates one
MiddlewareWithConfig(cfg) Configurable middleware with custom header, ID generator, and logging

Development

go test ./...
go vet ./...

License

MIT

Documentation

Overview

Package ctxlog provides context-aware structured logging helpers for Go's log/slog.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CorrelationID added in v0.2.0

func CorrelationID(ctx context.Context) string

CorrelationID extracts the correlation ID from the context. Returns an empty string if no correlation ID has been set.

func Fields added in v0.2.0

func Fields(ctx context.Context) []slog.Attr

Fields extracts all typed slog.Attr values stored in the context via WithAttrs. Returns nil if no attributes have been set.

func From

func From(ctx context.Context, logger *slog.Logger) *slog.Logger

From enriches the provided logger with all fields, attributes, and request ID stored in the context.

func Logger

func Logger(ctx context.Context) *slog.Logger

Logger returns slog.Default() enriched with all fields, attributes, and request ID stored in the context.

func Middleware

func Middleware(next http.Handler) http.Handler

Middleware generates a UUID v4 request ID, injects it into the request context via WithRequestID, and sets the X-Request-ID response header.

func MiddlewareWithConfig added in v0.2.0

func MiddlewareWithConfig(cfg MiddlewareConfig) func(http.Handler) http.Handler

MiddlewareWithConfig returns middleware configured with the provided options. Zero-value fields use sensible defaults: HeaderName defaults to "X-Request-ID" and GenerateID defaults to UUID v4 generation.

func MiddlewareWithHeader

func MiddlewareWithHeader(headerName string) func(http.Handler) http.Handler

MiddlewareWithHeader returns middleware that reads the request ID from the specified header. If the header is present and non-empty, its value is used; otherwise a new UUID v4 is generated. The request ID is injected into the context and set as the X-Request-ID response header.

func RequestID

func RequestID(ctx context.Context) string

RequestID extracts the request ID from the context. Returns an empty string if no request ID has been set.

func TraceID added in v0.2.0

func TraceID(ctx context.Context) string

TraceID extracts the trace ID from the context. Returns an empty string if no trace ID has been set.

func With

func With(ctx context.Context, args ...any) context.Context

With attaches slog key-value pairs to the context. The args should be alternating key-value pairs as accepted by slog.Logger.With. Multiple calls to With accumulate fields.

func WithAttrs

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

WithAttrs attaches typed slog.Attr values to the context. Multiple calls to WithAttrs accumulate attributes.

func WithCorrelationID added in v0.2.0

func WithCorrelationID(ctx context.Context, id string) context.Context

WithCorrelationID attaches a correlation ID to the context. Correlation IDs are used to group related requests across services.

func WithRequestID

func WithRequestID(ctx context.Context, id string) context.Context

WithRequestID attaches a request ID to the context.

func WithTraceID added in v0.2.0

func WithTraceID(ctx context.Context, id string) context.Context

WithTraceID attaches a trace ID to the context. Trace IDs are used for distributed tracing across service boundaries.

Types

type MiddlewareConfig added in v0.2.0

type MiddlewareConfig struct {
	HeaderName   string        // request ID header (default "X-Request-ID")
	GenerateID   func() string // custom ID generator (default UUID v4)
	LogRequests  bool          // log incoming requests
	LogResponses bool          // log completed responses
}

MiddlewareConfig configures the behavior of MiddlewareWithConfig.

Jump to

Keyboard shortcuts

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