Search and commands

↑ ↓ to select · Enter to open · Esc to close

Type to search packages.

logging

v0.7.1
rivaas.dev/logging

Documentation

pkg.go.dev ↗

Table of contents

↓ to select · Enter to jump· Shift+Enter for source

130 matches

Top ↑

Package logging provides structured logging with multiple provider backends.

Design philosophy: This package abstracts logging providers to enable:

  • Zero-dependency default (slog in stdlib)
  • Drop-in replacements for existing logging infrastructure
  • Testing with in-memory or no-op providers

The abstraction enables operational flexibility: production systems can switch providers without code changes (e.g., migrating from ELK to Datadog, or adding sampling in high-traffic systems).

The logging package follows the functional options pattern:

  • Options apply to an internal config struct
  • New() validates the config and builds the Logger from it
  • New() returns (*Logger, error); MustNew() panics on error

Basic Usage

logger := logging.MustNew(logging.WithConsoleHandler())
defer logger.Shutdown(context.Background())
logger.Info("service started", "port", 8080)

Structured Logging

logger := logging.MustNew(
    logging.WithJSONHandler(),
    logging.WithServiceName("my-service"),
    logging.WithDebugLevel(),
)
defer logger.Shutdown(context.Background())
logger.Info("request processed",
    "method", http.MethodGet,
    "path", "/api/users",
    "status", 200,
)

Convenience Methods

The package provides helper methods for common logging patterns:

// HTTP request logging
logger.LogRequest(r, "status", 200, "duration_ms", 45)

// Error logging with context
logger.LogError(err, "operation failed", "user_id", userID)

// Duration tracking
start := time.Now()
logger.LogDuration("processing completed", start, "items", count)

Log Sampling

Reduce log volume in high-traffic scenarios:

logger := logging.MustNew(
    logging.WithJSONHandler(),
    logging.WithSamplingInitial(100),        // Log first 100 entries
    logging.WithSamplingThereafter(100),    // Then log 1 in 100
    logging.WithSamplingTick(time.Minute),  // Reset every minute
)

Note: Errors (level >= ERROR) always bypass sampling.

Dynamic Log Levels

Change log levels at runtime:

logger.SetLevel(logging.LevelDebug)  // Enable debug logging
logger.SetLevel(logging.LevelWarn)   // Reduce to warnings only

Global Logger Registration

To register as the global slog default (for use with slog.Info(), etc.):

logger := logging.MustNew(
    logging.WithJSONHandler(),
    logging.WithGlobalLogger(), // Sets slog.SetDefault()
)

By default, loggers are NOT registered globally to allow multiple independent logger instances in the same process.

Sensitive Data Redaction

Sensitive data (password, token, secret, api_key, authorization) is automatically redacted from all log output. Additional sanitization can be configured using WithReplaceAttr.

Context-Aware Logging

Trace correlation with OpenTelemetry is automatic. When using slog.*Context methods with a context that contains an active OTel span, trace_id and span_id are injected into every log record:

slog.InfoContext(ctx, "processing request", "user_id", userID)
// Automatically includes trace_id and span_id if context has active span

Standalone Usage

This package works independently without the full Rivaas framework. Use it with any Go application.

See the README for more examples and configuration options.

Constants

LevelDebug (4 declarations)

const (
	// LevelDebug is the debug log level.
	LevelDebug = slog.LevelDebug
	LevelInfo  = slog.LevelInfo
	LevelWarn  = slog.LevelWarn
	LevelError = slog.LevelError
)

Variables

ErrNilLogger (5 declarations)

var (
	// ErrNilLogger indicates a nil custom logger was provided to [WithCustomLogger].
	// This is a programmer error and should be caught during initialization.
	ErrNilLogger = errors.New("custom logger is nil")

	// ErrInvalidHandler indicates an unsupported handler type was specified.
	// Valid types: JSONHandler, TextHandler, ConsoleHandler.
	ErrInvalidHandler = errors.New("invalid handler type")

	// ErrLoggerShutdown indicates the logger has been shut down via [Logger.Shutdown].
	// Further log attempts are silently dropped (not an error condition).
	// This error is returned by operations that require an active logger.
	ErrLoggerShutdown = errors.New("logger is shut down")

	// ErrInvalidLevel indicates an invalid log level was provided.
	// Valid levels: LevelDebug, LevelInfo, LevelWarn, LevelError.
	ErrInvalidLevel = errors.New("invalid log level")

	// ErrCannotChangeLevel indicates log level cannot be changed dynamically.
	// Returned by [Logger.SetLevel] when using a custom logger (level controlled externally).
	ErrCannotChangeLevel = errors.New("cannot change level on custom logger")
)

Error types for better error handling and testing.

Design rationale:

  • Sentinel errors (package-level vars) enable errors.Is checks
  • Descriptive names make error handling self-documenting
  • Explicit error types improve testability vs string comparison

Usage pattern:

if err := logger.SetLevel(level); err != nil {
    if errors.Is(err, logging.ErrCannotChangeLevel) {
        // Handle immutable logger case
    } else {
        // Handle other errors
    }
}

Functions

ExampleTestHelper

func ExampleTestHelper()

ExampleTestHelper demonstrates using the test helper.

Types

BatchLogger

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

BatchLogger accumulates log records and flushes them in batches.

Instead of writing each log entry immediately, entries are accumulated and written together.

Trade-offs:

  • Latency: Adds delay before logs appear (up to flush interval)
  • Memory: Buffers entries until flush
  • Durability: Crash before flush loses buffered entries

Mitigation strategies:

  • Periodic flush timer (logs appear within timeout even if batch not full)
  • Crash recovery: External log aggregation systems provide durability
  • Critical logs: Use synchronous logging for audit trails

Typical configuration:

  • Batch size: 100-1000 entries
  • Flush interval: 1-5 seconds

Thread-safe: Safe to use concurrently by multiple goroutines.

NewBatchLogger

func NewBatchLogger(logger *Logger, batchSize int, flushInterval time.Duration) *BatchLogger

NewBatchLogger creates a logger that batches entries before writing.

Parameters:

  • logger: Underlying Logger for final output
  • batchSize: Maximum entries before automatic flush (typical: 100-1000)
  • flushInterval: Maximum time between flushes (typical: 1-5 seconds)

Choosing batchSize:

  • Too small (< 10): May not provide meaningful batching
  • Too large (> 10000): Increases memory usage and delays
  • Typical: 100-1000 for most applications

Choosing flushInterval:

  • Too short (< 100ms): May not provide meaningful batching
  • Too long (> 30s): Unacceptable log delay
  • Typical: 1-5 seconds for most applications

Example:

logger := logging.MustNew(logging.WithJSONHandler())
batchLogger := logging.NewBatchLogger(logger, 100, time.Second)
defer batchLogger.Close()

// High-frequency logging
for i := 0; i < 10000; i++ {
    batchLogger.Info("high frequency event", "id", i)
}
// Logs are written in batches of 100 or every 1 second

Example

ExampleNewBatchLogger demonstrates batched logging for performance.
{
	logger := logging.MustNew(
		logging.WithJSONHandler(),
		logging.WithOutput(io.Discard),
	)

	defer logger.Shutdown(context.Background())

	bl := logging.NewBatchLogger(logger, 100, time.Second)
	defer bl.Close()

	bl.Info("first event")
	bl.Info("second event")

	fmt.Printf("batch size: %d\n", bl.Size())

	bl.Flush()

	fmt.Printf("after flush: %d\n", bl.Size())

}
Output:
batch size: 2
after flush: 0

BatchLogger.Close

func (bl *BatchLogger) Close()

Close stops the batch logger and flushes any remaining entries.

Important: Always call Close() to ensure buffered entries are written. Use defer immediately after creating the BatchLogger:

batchLogger := logging.NewBatchLogger(cfg, 100, time.Second)
defer batchLogger.Close()

Failure to call Close() will result in lost log entries (up to batchSize).

BatchLogger.Debug

func (bl *BatchLogger) Debug(msg string, args ...any)

Debug logs a debug message (batched). The msg and args are held in memory until the batch is flushed.

BatchLogger.Error

func (bl *BatchLogger) Error(msg string, args ...any)

Error logs an error message (batched). The msg and args are held in memory until the batch is flushed.

BatchLogger.Flush

func (bl *BatchLogger) Flush()

Flush writes all batched entries to the underlying logger.

BatchLogger.Info

func (bl *BatchLogger) Info(msg string, args ...any)

Info logs an info message (batched). The msg and args are held in memory until the batch is flushed.

BatchLogger.Size

func (bl *BatchLogger) Size() int

Size returns the current number of batched entries.

BatchLogger.Warn

func (bl *BatchLogger) Warn(msg string, args ...any)

Warn logs a warning message (batched). The msg and args are held in memory until the batch is flushed.

CountingWriter

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

CountingWriter counts bytes written without storing them.

Use cases:

  • Tests that need to verify log volume without storing content
  • Volume verification without memory constraints
  • Long-running tests that would exhaust memory with MockWriter

Example:

cw := &CountingWriter{}
logger := logging.MustNew(logging.WithOutput(cw))

for i := 0; i < 1000000; i++ {
    logger.Info("test")
}

t.Logf("Total bytes logged: %d", cw.Count())

CountingWriter.Count

func (cw *CountingWriter) Count() int64

Count returns the total bytes written.

CountingWriter.Write

func (cw *CountingWriter) Write(p []byte) (n int, err error)

Write implements io.Writer.

HandlerSpy

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

HandlerSpy implements slog.Handler and records all Handle calls for testing.

Use cases:

  • Test custom handler implementations
  • Verify handler receives expected records
  • Test handler filtering logic
  • Verify attribute and group handling

Example:

spy := &HandlerSpy{}
logger := slog.New(spy)

logger.Info("test", "key", "value")

if spy.RecordCount() != 1 {
    t.Error("expected one record")
}

records := spy.Records()
if records[0].Message != "test" {
    t.Error("unexpected message")
}

HandlerSpy.Enabled

func (hs *HandlerSpy) Enabled(_ context.Context, _ slog.Level) bool

Enabled implements slog.Handler.Enabled.

HandlerSpy.Handle

func (hs *HandlerSpy) Handle(_ context.Context, r slog.Record) error

Handle implements slog.Handler.Handle.

HandlerSpy.RecordCount

func (hs *HandlerSpy) RecordCount() int

RecordCount returns the number of captured records.

HandlerSpy.Records

func (hs *HandlerSpy) Records() []slog.Record

Records returns all captured records.

HandlerSpy.Reset

func (hs *HandlerSpy) Reset()

Reset clears all captured records.

HandlerSpy.WithAttrs

func (hs *HandlerSpy) WithAttrs(_ []slog.Attr) slog.Handler

WithAttrs implements slog.Handler.WithAttrs.

HandlerSpy.WithGroup

func (hs *HandlerSpy) WithGroup(_ string) slog.Handler

WithGroup implements slog.Handler.WithGroup.

HandlerType

type HandlerType string

HandlerType represents the type of logging handler.

JSONHandler (3 declarations)

const (
	// JSONHandler outputs structured JSON logs.
	JSONHandler HandlerType = "json"
	// TextHandler outputs key=value text logs.
	TextHandler HandlerType = "text"
	// ConsoleHandler outputs human-readable colored logs.
	ConsoleHandler HandlerType = "console"
)

Level

type Level = slog.Level

Level represents log level.

LogEntry

type LogEntry struct {
	Time    time.Time
	Level   string
	Message string
	Attrs   map[string]any
}

LogEntry represents a parsed log entry for testing.

ParseJSONLogEntries

func ParseJSONLogEntries(buf *bytes.Buffer) ([]LogEntry, error)

ParseJSONLogEntries parses JSON log entries from buffer into LogEntry slices. It creates a copy of the buffer so the original is not consumed.

Example

ExampleParseJSONLogEntries demonstrates parsing JSON log entries from a buffer.
{
	buf := &bytes.Buffer{}
	logger := logging.MustNew(
		logging.WithJSONHandler(),
		logging.WithOutput(buf),
	)

	defer logger.Shutdown(context.Background())

	logger.Info("first message")
	logger.Warn("second message", "count", 42)

	entries, err := logging.ParseJSONLogEntries(buf)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	fmt.Printf("entry count: %d\n", len(entries))
	fmt.Printf("first level: %s\n", entries[0].Level)
	fmt.Printf("second level: %s\n", entries[1].Level)

}
Output:
entry count: 2
first level: INFO
second level: WARN

Logger

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

Logger is the main logging type that provides structured logging capabilities.

Thread-safety: All public methods are safe for concurrent use. The slogger field is accessed atomically, while mu protects initialization and reconfiguration operations.

Example (contextAwareLogging)

ExampleLogger\_contextAwareLogging demonstrates automatic trace injection via context.
{
	buf := &bytes.Buffer{}
	logger := logging.MustNew(
		logging.WithJSONHandler(),
		logging.WithOutput(buf),
	)

	defer logger.Shutdown(context.Background())

	slogger := logger.Logger().With("request_id", "req-123", "user_id", "user-456")

	ctx := context.Background()
	slogger.InfoContext(ctx, "processing request")

	entries, _ := logging.ParseJSONLogEntries(buf)
	fmt.Printf("request_id: %s\n", entries[0].Attrs["request_id"])
	fmt.Printf("user_id: %s\n", entries[0].Attrs["user_id"])

}
Output:
request_id: req-123
user_id: user-456

MustNew

func MustNew(opts ...Option) *Logger

MustNew creates a new Logger or panics on error.

Example

ExampleMustNew demonstrates creating a logger that panics on error. This is useful for application initialization where errors are fatal.
{
	logger := logging.MustNew(
		logging.WithConsoleHandler(),
		logging.WithDebugLevel(),
	)

	defer logger.Shutdown(context.Background())

	logger.Info("application initialized")
	logger.Debug("debug information", "key", "value")

}

New

func New(opts ...Option) (*Logger, error)

New creates a new Logger with the given options.

By default, this function does NOT set the global slog default logger. Use WithGlobalLogger() if you want to register this logger as the global default.

This allows multiple Logger instances to coexist in the same process, and makes it easier to integrate Rivaas into larger binaries that already manage their own global logger.

Example

ExampleNew demonstrates creating a new logger with basic configuration. The logger outputs JSON-formatted logs to stdout.
{
	logger, err := logging.New(
		logging.WithJSONHandler(),
		logging.WithServiceName("my-service"),
		logging.WithServiceVersion("1.0.0"),
	)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	defer logger.Shutdown(context.Background())

	logger.Info("service started", "port", 8080)

}

Example (validation)

ExampleNew\_validation demonstrates that New validates configuration.
{
	_, err := logging.New(logging.WithOutput(nil))
	if err != nil {
		fmt.Println("validation error:", err != nil)
	}

}
Output:
validation error: true

NewTestLogger

func NewTestLogger() (*Logger, *bytes.Buffer)

NewTestLogger creates a Logger for testing with an in-memory buffer. The returned buffer can be used with ParseJSONLogEntries to inspect log output.

Example

ExampleNewTestLogger demonstrates creating a logger for testing.
{
	logger, buf := logging.NewTestLogger()
	defer logger.Shutdown(context.Background())

	logger.Info("test message", "key", "value")

	entries, _ := logging.ParseJSONLogEntries(buf)
	fmt.Printf("logged %d entries\n", len(entries))
	fmt.Printf("message: %s\n", entries[0].Message)

}
Output:
logged 1 entries
message: test message

Logger.Debug

func (l *Logger) Debug(msg string, args ...any)

Debug logs a debug message with structured attributes. Thread-safe and safe to call concurrently.

Logger.DebugInfo

func (l *Logger) DebugInfo() map[string]any

DebugInfo returns diagnostic information about the logger.

Logger.Environment

func (l *Logger) Environment() string

Environment returns the environment. This field is immutable after initialization, so no lock is needed.

Logger.Error

func (l *Logger) Error(msg string, args ...any)

Error logs an error message with structured attributes. Thread-safe and safe to call concurrently. Note: Errors bypass sampling and are always logged.

Logger.ErrorWithStack

func (l *Logger) ErrorWithStack(msg string, err error, includeStack bool, extra ...any)

ErrorWithStack logs an error with optional stack trace.

When to use stack traces:

✓ Critical errors that require debugging
✓ Unexpected error conditions (panics, invariant violations)
✗ Expected errors (validation failures, not found)
✗ High-frequency errors where stack capture cost is undesirable

Thread-safe and safe to call concurrently.

Example

ExampleLogger\_ErrorWithStack demonstrates error logging with stack traces. Stack traces should only be enabled for critical errors to avoid performance overhead.
{
	logger := logging.MustNew(logging.WithConsoleHandler())
	defer logger.Shutdown(context.Background())

	err := errors.New("critical error occurred")
	logger.ErrorWithStack("critical error", err, true,
		"component", "payment-processor",
		"transaction_id", "tx-12345",
	)
}

Logger.FlushBuffer

func (l *Logger) FlushBuffer() error

FlushBuffer replays all buffered log records to the output and disables buffering. If buffering was not enabled, this is a no-op.

Example:

logger.StartBuffering()
// ... initialization that produces logs ...
printBanner()
logger.FlushBuffer() // Now all startup logs appear after the banner

Logger.Info

func (l *Logger) Info(msg string, args ...any)

Info logs an informational message with structured attributes. Thread-safe and safe to call concurrently.

Logger.IsBuffering

func (l *Logger) IsBuffering() bool

IsBuffering returns whether the logger is currently buffering logs.

Logger.IsEnabled

func (l *Logger) IsEnabled() bool

IsEnabled returns true if logging is enabled and not shutting down.

Example

ExampleLogger\_IsEnabled demonstrates checking if logging is enabled.
{
	logger := logging.MustNew(
		logging.WithJSONHandler(),
		logging.WithOutput(io.Discard),
	)

	fmt.Printf("before shutdown: %v\n", logger.IsEnabled())

	logger.Shutdown(context.Background())

	fmt.Printf("after shutdown: %v\n", logger.IsEnabled())

}
Output:
before shutdown: true
after shutdown: false

Logger.Level

func (l *Logger) Level() Level

Level returns the current minimum log level. Note: This requires a lock because level can be changed dynamically via SetLevel.

Example

ExampleLogger\_Level demonstrates accessing and checking the log level.
{
	logger := logging.MustNew(
		logging.WithJSONHandler(),
		logging.WithOutput(io.Discard),
		logging.WithLevel(logging.LevelWarn),
	)

	defer logger.Shutdown(context.Background())

	level := logger.Level()
	fmt.Printf("level: %s\n", level.String())

}
Output:
level: WARN

Logger.LogDuration

func (l *Logger) LogDuration(msg string, start time.Time, extra ...any)

LogDuration logs an operation duration with timing information.

Automatically includes:

  • duration_ms: Duration in milliseconds (for easy filtering/alerting)
  • duration: Human-readable duration string (e.g., "1.5s", "250ms")

Thread-safe and safe to call concurrently.

Example:

start := time.Now()
result, err := processData(data)
logger.LogDuration("data processing completed", start,
    "rows_processed", result.Count,
    "errors", result.Errors,
)

Example

ExampleLogger\_LogDuration demonstrates logging operation duration. Both human-readable duration and milliseconds are automatically included.
{
	logger := logging.MustNew(logging.WithJSONHandler())
	defer logger.Shutdown(context.Background())

	start := time.Now()

	time.Sleep(10 * time.Millisecond)

	logger.LogDuration("data processing completed", start,
		"rows_processed", 1000,
		"errors", 0,
	)

}

Logger.LogError

func (l *Logger) LogError(err error, msg string, extra ...any)

LogError logs an error with additional context fields.

Why use this instead of Error():

  • Automatically includes "error" field with error message
  • Convenient for error handling patterns
  • Consistent error logging format across codebase

Thread-safe and safe to call concurrently.

Example:

if err := db.Insert(user); err != nil {
    logger.LogError(err, "database operation failed",
        "operation", "INSERT",
        "table", "users",
        "retry_count", 3,
    )
    return err
}

Example

ExampleLogger\_LogError demonstrates logging errors with context. The error message is automatically added as the "error" attribute.
{
	logger := logging.MustNew(logging.WithConsoleHandler())

	defer logger.Shutdown(context.Background())

	err := errors.New("database connection failed")
	logger.LogError(err, "database operation failed",
		"operation", "INSERT",
		"table", "users",
		"retry_count", 3,
	)

}

Logger.LogRequest

func (l *Logger) LogRequest(r *http.Request, extra ...any)

LogRequest logs an HTTP request with standard fields.

Standard fields included:

  • method: HTTP method (GET, POST, etc.)
  • path: Request path (without query string)
  • remote: Client remote address
  • user_agent: Client User-Agent header
  • query: Query string (only if non-empty)

Additional fields can be passed via 'extra' (e.g., "status", 200, "duration_ms", 45).

Thread-safe and safe to call concurrently.

Example:

logger.LogRequest(r, "status", 200, "duration_ms", 45, "bytes", 1024)

Example

ExampleLogger\_LogRequest demonstrates logging HTTP requests. This helper method automatically extracts common request fields.
{
	ctx := context.Background()
	logger := logging.MustNew(logging.WithJSONHandler())

	defer logger.Shutdown(ctx)

	req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "/api/users?page=1", nil)
	req.RemoteAddr = "192.168.1.1:12345"
	req.Header.Set("User-Agent", "MyApp/1.0")

	logger.LogRequest(req, "status", 200, "duration_ms", 45)

}

Logger.Logger

func (l *Logger) Logger() *slog.Logger

Logger returns the underlying slog.Logger. This method is safe for concurrent access.

Logger.ServiceName

func (l *Logger) ServiceName() string

ServiceName returns the service name. This field is immutable after initialization, so no lock is needed.

Example

ExampleLogger\_ServiceName demonstrates accessing logger configuration.
{
	logger := logging.MustNew(
		logging.WithJSONHandler(),
		logging.WithOutput(io.Discard),
		logging.WithServiceName("my-api"),
		logging.WithServiceVersion("2.0.0"),
		logging.WithEnvironment("production"),
	)

	defer logger.Shutdown(context.Background())

	fmt.Printf("service: %s\n", logger.ServiceName())
	fmt.Printf("version: %s\n", logger.ServiceVersion())
	fmt.Printf("env: %s\n", logger.Environment())

}
Output:
service: my-api
version: 2.0.0
env: production

Logger.ServiceVersion

func (l *Logger) ServiceVersion() string

ServiceVersion returns the service version. This field is immutable after initialization, so no lock is needed.

Logger.SetLevel

func (l *Logger) SetLevel(level Level) error

SetLevel dynamically changes the minimum log level at runtime.

Use cases:

  • Enable debug logging temporarily for troubleshooting
  • Reduce log volume during high traffic periods
  • Runtime configuration via HTTP endpoint or signal handler

Limitations:

  • Not supported with custom loggers (returns ErrCannotChangeLevel)
  • Brief initialization window where old/new levels may race

Thread-safe: Safe to call concurrently, but multiple SetLevel calls will serialize.

Example

ExampleLogger\_SetLevel demonstrates dynamic level changes at runtime.
{
	logger := logging.MustNew(
		logging.WithJSONHandler(),
		logging.WithOutput(io.Discard),
		logging.WithLevel(logging.LevelInfo),
	)

	defer logger.Shutdown(context.Background())

	fmt.Printf("initial: %s\n", logger.Level().String())

	err := logger.SetLevel(logging.LevelDebug)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	fmt.Printf("changed: %s\n", logger.Level().String())

}
Output:
initial: INFO
changed: DEBUG

Logger.Shutdown

func (l *Logger) Shutdown(_ context.Context) error

Shutdown gracefully shuts down the logger.

Logger.StartBuffering

func (l *Logger) StartBuffering()

StartBuffering enables log buffering on the logger. While buffering is enabled, log records are stored in memory instead of being written. Call FlushBuffer to replay all buffered logs to the output.

This is useful for delaying startup logs until after a banner or other output is printed.

Example:

logger.StartBuffering()
// ... initialization that produces logs ...
printBanner()
logger.FlushBuffer()

Logger.Warn

func (l *Logger) Warn(msg string, args ...any)

Warn logs a warning message with structured attributes. Thread-safe and safe to call concurrently.

Logger.With

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

With returns a slog.Logger with additional attributes.

Logger.WithGroup

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

WithGroup returns a slog.Logger with a group name.

MockWriter

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

MockWriter is a mock io.Writer that records all writes for test assertions.

Use cases:

  • Verify number of write calls (batching behavior)
  • Inspect write contents (log format validation)
  • Simulate write errors (error handling tests)

Example:

mw := &MockWriter{}
logger := logging.MustNew(logging.WithOutput(mw))
logger.Info("test")

if mw.WriteCount() != 1 {
    t.Error("expected exactly one write")
}

MockWriter.BytesWritten

func (mw *MockWriter) BytesWritten() int

BytesWritten returns total bytes written.

MockWriter.LastWrite

func (mw *MockWriter) LastWrite() []byte

LastWrite returns the most recent write.

MockWriter.Reset

func (mw *MockWriter) Reset()

Reset clears all recorded writes.

MockWriter.Write

func (mw *MockWriter) Write(p []byte) (n int, err error)

Write implements io.Writer.

MockWriter.WriteCount

func (mw *MockWriter) WriteCount() int

WriteCount returns the number of write calls.

Option

type Option func(*config)

Option is a functional option for configuring the logger. Options apply to an internal config struct; the constructor builds the Logger from the validated config.

WithConsoleHandler

func WithConsoleHandler() Option

WithConsoleHandler uses human-readable console logging.

WithCustomLogger

func WithCustomLogger(customLogger *slog.Logger) Option

WithCustomLogger uses a custom slog.Logger instead of creating one. When using a custom logger, Logger.SetLevel is not supported.

WithDebugLevel

func WithDebugLevel() Option

WithDebugLevel enables debug logging.

WithDebugMode

func WithDebugMode(enabled bool) Option

WithDebugMode enables verbose debugging information.

WithEnvironment

func WithEnvironment(env string) Option

WithEnvironment sets the environment. When set, the environment is automatically added to all log entries.

WithGlobalLogger

func WithGlobalLogger() Option

WithGlobalLogger registers this logger as the global slog default logger. By default, loggers are not registered globally to allow multiple logger instances to coexist in the same process.

Example:

logger := logging.MustNew(
    logging.WithJSONHandler(),
    logging.WithGlobalLogger(), // Register as global default
)

WithHandlerType

func WithHandlerType(t HandlerType) Option

WithHandlerType sets the logging handler type.

WithJSONHandler

func WithJSONHandler() Option

WithJSONHandler uses JSON structured logging (default).

WithLevel

func WithLevel(level Level) Option

WithLevel sets the minimum log level.

WithOutput

func WithOutput(w io.Writer) Option

WithOutput sets the output writer.

WithReplaceAttr

func WithReplaceAttr(fn func(groups []string, a slog.Attr) slog.Attr) Option

WithReplaceAttr sets a custom attribute replacer function. The function receives groups and an slog.Attr, and returns a modified attribute. Return an empty slog.Attr to drop the attribute from output.

Example

ExampleWithReplaceAttr demonstrates custom attribute replacement. This is useful for custom redaction rules beyond the built-in sensitive fields.
{
	logger := logging.MustNew(
		logging.WithJSONHandler(),
		logging.WithReplaceAttr(func(groups []string, a slog.Attr) slog.Attr {

			if a.Key == "password" || a.Key == "token" {
				return slog.String(a.Key, "***REDACTED***")
			}

			return a
		}),
	)

	defer logger.Shutdown(context.Background())

	logger.Info("user login", "username", "alice", "password", "secret123")

}

WithSamplingInitial

func WithSamplingInitial(initial int) Option

WithSamplingInitial sets how many log entries to emit unconditionally before sampling. Only has effect when used together with WithSamplingThereafter and/or WithSamplingTick. Zero means no initial burst. Must be non-negative (validated at construction).

Example

ExampleWithSamplingInitial demonstrates log sampling for high-traffic scenarios. Use WithSamplingInitial, WithSamplingThereafter, and WithSamplingTick together to control initial burst, sampling rate, and counter reset interval.
{
	logger := logging.MustNew(
		logging.WithJSONHandler(),
		logging.WithSamplingInitial(100),
		logging.WithSamplingThereafter(100),
		logging.WithSamplingTick(time.Minute),
	)

	defer logger.Shutdown(context.Background())

	for i := range 500 {
		logger.Info("request processed", "request_id", i)
	}

}

WithSamplingThereafter

func WithSamplingThereafter(thereafter int) Option

WithSamplingThereafter sets the sampling rate after the initial burst: log 1 in every N entries. Zero means log all after the initial phase. Must be non-negative (validated at construction).

WithSamplingTick

func WithSamplingTick(tick time.Duration) Option

WithSamplingTick sets the interval at which the sampling counter is reset. Zero means never reset. Enables sampling when set (with or without other sampling options).

WithServiceName

func WithServiceName(name string) Option

WithServiceName sets the service name. When set, the service name is automatically added to all log entries.

WithServiceVersion

func WithServiceVersion(version string) Option

WithServiceVersion sets the service version. When set, the version is automatically added to all log entries.

WithSource

func WithSource(enabled bool) Option

WithSource enables source code location in logs.

WithTextHandler

func WithTextHandler() Option

WithTextHandler uses text key=value logging.

SlowWriter

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

SlowWriter simulates slow I/O for testing timeouts and backpressure.

Use cases:

  • Test timeout handling in logging middleware
  • Simulate network latency in distributed logging
  • Verify non-blocking behavior under slow I/O
  • Test context cancellation during logging

Example:

// Simulate 100ms network latency
sw := NewSlowWriter(100*time.Millisecond, &bytes.Buffer{})
logger := logging.MustNew(logging.WithOutput(sw))

start := time.Now()
logger.Info("test")
duration := time.Since(start)

if duration < 100*time.Millisecond {
    t.Error("expected write to be delayed")
}

NewSlowWriter

func NewSlowWriter(delay time.Duration, inner io.Writer) *SlowWriter

NewSlowWriter creates a writer that delays each write.

SlowWriter.Write

func (sw *SlowWriter) Write(p []byte) (n int, err error)

Write implements io.Writer with delay.

TestHelper

type TestHelper struct {
	Logger *Logger
	Buffer *bytes.Buffer
}

TestHelper provides utilities for testing with the logging package.

NewTestHelper

func NewTestHelper(t *testing.T, opts ...Option) *TestHelper

NewTestHelper creates a TestHelper with in-memory logging. Additional Option values can be passed to customize the logger.

TestHelper.AssertLog

func (th *TestHelper) AssertLog(t *testing.T, level, msg string, attrs map[string]any)

AssertLog checks that a log entry exists with the given properties.

TestHelper.ContainsAttr

func (th *TestHelper) ContainsAttr(key string, value any) bool

ContainsAttr checks if any log entry contains the given attribute.

TestHelper.ContainsLog

func (th *TestHelper) ContainsLog(msg string) bool

ContainsLog checks if any log entry contains the given message.

TestHelper.CountLevel

func (th *TestHelper) CountLevel(level string) int

CountLevel returns the number of log entries at the given level.

TestHelper.LastLog

func (th *TestHelper) LastLog() (*LogEntry, error)

LastLog returns the most recent log entry.

TestHelper.Logs

func (th *TestHelper) Logs() ([]LogEntry, error)

Logs returns all parsed log entries.

TestHelper.Reset

func (th *TestHelper) Reset()

Reset clears the buffer for fresh testing.

Dependency graph