logging

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package logging provides structured logging with request tracing and sensitive data redaction.

Index

Constants

View Source
const (
	// RequestIDKey is the context key for request IDs.
	RequestIDKey contextKey = "request_id"
	// TraceIDKey is the context key for trace IDs.
	TraceIDKey contextKey = "trace_id"
	// UserIDKey is the context key for user IDs.
	UserIDKey contextKey = "user_id"
	// SpanIDKey is the context key for span IDs.
	SpanIDKey contextKey = "span_id"
)
View Source
const RedactedValue = "[REDACTED]"
View Source
const RequestHeaderRequestID = "X-Request-ID"

RequestHeaderRequestID is the header name for request ID.

View Source
const RequestHeaderTraceID = "X-Trace-ID"

RequestHeaderTraceID is the header name for trace ID.

Variables

This section is empty.

Functions

func GenerateRequestID

func GenerateRequestID() string

GenerateRequestID generates a new UUID v4 request ID.

func GenerateSpanID

func GenerateSpanID() string

GenerateSpanID generates a new UUID v4 span ID.

func GetRequestID

func GetRequestID(ctx context.Context) string

GetRequestID retrieves the request ID from the context.

func GetSpanID

func GetSpanID(ctx context.Context) string

GetSpanID retrieves the span ID from the context.

func GetTraceID

func GetTraceID(ctx context.Context) string

GetTraceID retrieves the trace ID from the context.

func GetUserID

func GetUserID(ctx context.Context) string

GetUserID retrieves the user ID from the context.

func InjectRequestID

func InjectRequestID(next http.Handler) http.Handler

InjectRequestID is a simple middleware that only injects request ID into context.

func IsSensitiveField

func IsSensitiveField(field string) bool

IsSensitiveField checks if a field name is sensitive using the default redactor.

func LoggerFromContext

func LoggerFromContext(ctx context.Context, baseLogger *slog.Logger) *slog.Logger

LoggerFromContext returns a logger with context values pre-populated.

func ModuleLogger

func ModuleLogger(module string) *slog.Logger

ModuleLogger creates a logger for a specific module using the default logger.

func ParseLevel

func ParseLevel(level string) slog.Level

ParseLevel converts a string level to slog.Level.

func RedactSensitive

func RedactSensitive(data map[string]any) map[string]any

RedactSensitive redacts sensitive fields from a map using the default redactor.

func RedactStringValue

func RedactStringValue(s string) string

RedactString redacts sensitive patterns from a string using the default redactor.

func RequestLogger

func RequestLogger(logger *slog.Logger) func(http.Handler) http.Handler

RequestLogger is a convenience function to create a middleware that logs requests.

func SafeAttrs

func SafeAttrs(data map[string]any) []slog.Attr

SafeAttrs creates slog attributes with sensitive data redacted using the default redactor.

func WithRequestID

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

WithRequestID adds a request ID to the context.

func WithSpanID

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

WithSpanID adds a span ID to the context.

func WithTraceID

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

WithTraceID adds a trace ID to the context.

func WithUserID

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

WithUserID adds a user ID to the context.

Types

type Config

type Config struct {
	// Level sets the minimum log level: debug, info, warn, error
	Level string

	// Format specifies the output format: json or text
	Format string

	// Output specifies the output destination: stdout, stderr, or a file path
	Output string

	// AddSource adds source file and line number to log entries
	AddSource bool

	// SampleRate for high-volume logs (0.0-1.0, 1.0 = log all)
	SampleRate float64

	// SlowQueryThreshold marks queries slower than this as slow
	SlowQueryThreshold time.Duration

	// RedactPatterns are additional patterns to redact
	RedactPatterns []string

	// AllowlistFields are field names that should not be redacted even if they match patterns
	AllowlistFields []string
}

Config holds the logging configuration.

func ConfigFromEnv

func ConfigFromEnv() Config

ConfigFromEnv creates a configuration from environment variables.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns sensible defaults for logging configuration.

func (Config) GetOutput

func (c Config) GetOutput() io.Writer

GetOutput returns the io.Writer for the configured output.

type ContextHandler

type ContextHandler struct {
	slog.Handler
	// contains filtered or unexported fields
}

ContextHandler is a slog.Handler that extracts context values.

func (*ContextHandler) Enabled

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

Enabled reports whether the handler handles records at the given level.

func (*ContextHandler) Handle

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

Handle adds context values to the log record and passes to the wrapped handler.

func (*ContextHandler) WithAttrs

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

WithAttrs returns a new ContextHandler with the given attributes.

func (*ContextHandler) WithGroup

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

WithGroup returns a new ContextHandler with the given group.

type HTTPMiddleware

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

HTTPMiddleware provides HTTP request logging middleware.

func NewHTTPMiddleware

func NewHTTPMiddleware(logger *slog.Logger) *HTTPMiddleware

NewHTTPMiddleware creates a new HTTP logging middleware.

func (*HTTPMiddleware) Handler

func (m *HTTPMiddleware) Handler(next http.Handler) http.Handler

Handler returns the middleware handler.

func (*HTTPMiddleware) WithVerbosity

func (m *HTTPMiddleware) WithVerbosity(v Verbosity) *HTTPMiddleware

WithVerbosity sets the logging verbosity level.

type Logger

type Logger struct {
	*slog.Logger
	// contains filtered or unexported fields
}

Logger wraps slog.Logger with additional functionality.

func Default

func Default() *Logger

Default returns a default logger using environment configuration.

func New

func New(config Config) *Logger

New creates a new Logger with the given configuration.

func NewWithWriter

func NewWithWriter(config Config, w io.Writer) *Logger

NewWithWriter creates a new Logger with a custom writer.

func (*Logger) SetDefault

func (l *Logger) SetDefault()

SetDefault sets this logger as the default slog logger.

func (*Logger) With

func (l *Logger) With(args ...any) *Logger

With returns a new Logger with the given attributes.

func (*Logger) WithEntity

func (l *Logger) WithEntity(entity, id string) *Logger

WithEntity returns a new Logger with entity context.

func (*Logger) WithGroup

func (l *Logger) WithGroup(name string) *Logger

WithGroup returns a new Logger with the given group name.

func (*Logger) WithJob

func (l *Logger) WithJob(jobID string) *Logger

WithJob returns a new Logger with job context.

func (*Logger) WithModule

func (l *Logger) WithModule(module string) *Logger

WithModule returns a new Logger with module context.

func (*Logger) WithOperation

func (l *Logger) WithOperation(operation string) *Logger

WithOperation returns a new Logger with operation context.

func (*Logger) WithWorkflow

func (l *Logger) WithWorkflow(workflowID, executionID string) *Logger

WithWorkflow returns a new Logger with workflow context.

type RedactingHandler

type RedactingHandler struct {
	slog.Handler
	// contains filtered or unexported fields
}

RedactingHandler wraps a slog.Handler to redact sensitive data from log records.

func NewRedactingHandler

func NewRedactingHandler(handler slog.Handler, redactor *Redactor) *RedactingHandler

NewRedactingHandler creates a new RedactingHandler.

func (*RedactingHandler) Handle

func (h *RedactingHandler) Handle(ctx context.Context, r slog.Record) error

Handle processes log records and redacts sensitive data.

func (*RedactingHandler) WithAttrs

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

WithAttrs returns a new RedactingHandler with the given attributes.

func (*RedactingHandler) WithGroup

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

WithGroup returns a new RedactingHandler with the given group.

type Redactor

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

Redactor handles redaction of sensitive data.

func NewRedactor

func NewRedactor() *Redactor

NewRedactor creates a new Redactor with default settings.

func (*Redactor) AddAllowlistField

func (r *Redactor) AddAllowlistField(field string)

AddAllowlistField adds a field to the allowlist (won't be redacted even if matching).

func (*Redactor) AddSensitiveField

func (r *Redactor) AddSensitiveField(field string)

AddSensitiveField adds a field name to the sensitive list.

func (*Redactor) AddSensitivePattern

func (r *Redactor) AddSensitivePattern(pattern string) error

AddSensitivePattern adds a regex pattern to detect sensitive data.

func (*Redactor) IsSensitiveField

func (r *Redactor) IsSensitiveField(field string) bool

IsSensitiveField checks if a field name is sensitive.

func (*Redactor) RedactMap

func (r *Redactor) RedactMap(data map[string]any) map[string]any

RedactMap redacts sensitive fields from a map recursively.

func (*Redactor) RedactString

func (r *Redactor) RedactString(s string) string

RedactString redacts sensitive patterns from a string.

func (*Redactor) SafeAttrs

func (r *Redactor) SafeAttrs(data map[string]any) []slog.Attr

SafeAttrs creates slog attributes with sensitive data redacted.

type TraceContext

type TraceContext struct {
	RequestID string
	TraceID   string
	SpanID    string
	UserID    string
}

TraceContext holds tracing information for a request.

func FromContext

func FromContext(ctx context.Context) TraceContext

FromContext extracts a TraceContext from a context.Context.

func NewTraceContext

func NewTraceContext() TraceContext

NewTraceContext creates a new TraceContext with generated IDs.

func NewTraceContextWithParent

func NewTraceContextWithParent(parentTraceID string) TraceContext

NewTraceContextWithParent creates a new TraceContext inheriting the parent trace ID.

func (TraceContext) ToContext

func (tc TraceContext) ToContext(ctx context.Context) context.Context

ToContext adds the trace context to a context.Context.

func (TraceContext) WithRequestID

func (tc TraceContext) WithRequestID(id string) TraceContext

WithRequestID sets the request ID.

func (TraceContext) WithSpanID

func (tc TraceContext) WithSpanID(id string) TraceContext

WithSpanID sets the span ID.

func (TraceContext) WithTraceID

func (tc TraceContext) WithTraceID(id string) TraceContext

WithTraceID sets the trace ID.

func (TraceContext) WithUserID

func (tc TraceContext) WithUserID(id string) TraceContext

WithUserID sets the user ID.

type Verbosity

type Verbosity int

Verbosity controls how much request/response detail is logged.

const (
	// VerbosityMinimal logs only method, path, status, and duration.
	VerbosityMinimal Verbosity = iota
	// VerbosityStandard logs additional request metadata.
	VerbosityStandard
	// VerbosityVerbose logs request/response headers.
	VerbosityVerbose
)

Jump to

Keyboard shortcuts

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