mock

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 6 Imported by: 0

README

Mock Logger Handler

The mock handler provides a Logger implementation that records log messages for testing and verification purposes. It is designed to help test other slog handlers and applications that use slog.

Overview

The mock handler consists of two main components:

  • Logger: A fully functional slog.Logger implementation that records messages instead of outputting them.
  • Recorder: A thread-safe storage system for capturing and retrieving log messages.

Usage

Basic Testing
import (
    "testing"
    "darvaza.org/slog"
    "darvaza.org/slog/handlers/mock"
)

func TestMyCode(t *testing.T) {
    // Create a mock logger.
    logger := mock.NewLogger()

    // Use it in your code.
    myFunction(logger)

    // Verify the logged messages.
    messages := logger.GetMessages()
    core.AssertMustEqual(t, 1, len(messages), "message count")

    msg := messages[0]
    core.AssertEqual(t, slog.Info, msg.Level, "log level")
    core.AssertEqual(t, "expected message", msg.Message, "log message")
}
Testing with Fields
func TestWithFields(t *testing.T) {
    logger := mock.NewLogger()

    logger.Info().
        WithField("user", "john").
        WithField("action", "login").
        Print("User logged in")

    messages := logger.GetMessages()
    msg := messages[0]

    // Check fields
    if msg.Fields["user"] != "john" {
        t.Errorf("expected user=john, got %v", msg.Fields["user"])
    }
    if msg.Fields["action"] != "login" {
        t.Errorf("expected action=login, got %v", msg.Fields["action"])
    }
}
Testing with Level Filtering

The mock logger supports threshold-based filtering for testing handlers that only process certain log levels:

package mock_test

import (
    "testing"

    "darvaza.org/core"
    "darvaza.org/slog"
    "darvaza.org/slog/handlers/mock"
)

func TestLevelFiltering(t *testing.T) {
    // Create logger that only records Info and above
    logger := mock.NewLoggerWithThreshold(slog.Info)

    logger.Debug().Print("debug message")  // Not recorded
    logger.Info().Print("info message")    // Recorded
    logger.Error().Print("error message")  // Recorded

    messages := logger.GetMessages()
    core.AssertEqual(t, 2, len(messages), "message count")
}
Testing Handler Adapters

The mock logger is particularly useful for testing adapter handlers that wrap other loggers:

func TestMyAdapter(t *testing.T) {
    // Create mock as backend
    backend := mock.NewLogger()

    // Create your adapter using the mock backend
    adapter := myadapter.New(backend)

    // Use the adapter
    adapter.Error().Print("Something went wrong")

    // Verify through the backend
    messages := backend.GetMessages()
    // ... verify messages were properly forwarded
}

API Reference

Logger
  • NewLogger() *Logger - Creates a new mock logger that records all levels.
  • NewLoggerWithThreshold(threshold slog.LogLevel) *Logger - Creates a new mock logger with level filtering.
  • GetMessages() []Message - Returns all recorded messages.
  • Clear() - Removes all recorded messages from this logger.
  • Implements all slog.Logger methods (Debug, Info, WithField, etc.).
Recorder
  • NewRecorder() *Recorder - Creates a new message recorder.
  • Record(msg Message) - Stores a message.
  • GetMessages() []Message - Returns all recorded messages.
  • Clear() - Removes all stored messages.
Message
  • Message struct contains:
    • Message string - The log message text.
    • Level slog.LogLevel - The log level.
    • Fields map[string]any - Attached fields.
    • Stack bool - Whether stack trace was requested.
  • String() string - Formatted string representation.

Features

  • Thread-safe: All operations are safe for concurrent use.
  • Immutable: Logger methods return new instances, preserving immutability.
  • Complete: Implements the full slog.Logger interface.
  • Field preservation: Maintains field chains correctly.
  • Stack tracking: Records when WithStack() was called.
  • Level filtering: Optional threshold filtering for testing specific log levels.
  • Backward compatible: Existing code using NewLogger() continues to work unchanged.

Design Notes

The mock logger is designed to be a faithful implementation of the slog.Logger interface whilst capturing all the information needed for testing. It preserves the immutable nature of loggers by creating new instances for each modification.

The recorder component is separate to allow for advanced testing scenarios where you might want to share a recorder between multiple logger instances or create custom recording strategies.

Level filtering uses the same logic as the filter handler: the zero value (UndefinedLevel) means no filtering occurs, maintaining backward compatibility. When a threshold is set, only messages at or above that level are recorded.

Documentation

Overview

Package mock provides a mock logger implementation for testing slog handlers.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Logger

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

Logger implements slog.Logger for testing purposes.

func NewLogger

func NewLogger() *Logger

NewLogger creates a new test logger with a recorder. By default, it logs all levels (no threshold filtering).

func NewLoggerWithThreshold added in v0.7.8

func NewLoggerWithThreshold(threshold slog.LogLevel) *Logger

NewLoggerWithThreshold creates a new test logger with a specific threshold. Only messages at or above the threshold level will be recorded.

func (*Logger) CallStack added in v0.8.0

func (l *Logger) CallStack() core.Stack

CallStack returns the call stack associated with this logger. This method is exposed for testing purposes.

func (*Logger) Clear

func (l *Logger) Clear()

Clear removes all recorded messages from this logger.

func (*Logger) Debug

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

Debug returns a logger with Debug level.

func (*Logger) Enabled

func (l *Logger) Enabled() bool

Enabled returns whether this logger is enabled and would record at its current level.

func (*Logger) Error

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

Error returns a logger with Error level.

func (*Logger) Fatal

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

Fatal returns a logger with Fatal level.

func (*Logger) Fields added in v0.8.0

func (l *Logger) Fields() *internal.FieldsIterator

Fields returns an iterator over all fields in the logger chain. This method is exposed for testing purposes.

func (*Logger) FieldsCount added in v0.8.0

func (l *Logger) FieldsCount() int

FieldsCount returns the total number of fields in the logger chain. This method is exposed for testing purposes.

func (*Logger) GetMessages

func (l *Logger) GetMessages() []Message

GetMessages returns all recorded messages from this logger.

func (*Logger) Info

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

Info returns a logger with Info level.

func (*Logger) Level added in v0.8.0

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

Level returns the current log level. Exposed for testing only.

func (*Logger) Panic

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

Panic returns a logger with Panic level.

func (*Logger) Print

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

Print implements slog.Logger.

func (*Logger) Printf

func (l *Logger) Printf(format string, args ...any)

Printf implements slog.Logger.

func (*Logger) Println

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

Println implements slog.Logger.

func (*Logger) Warn

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

Warn returns a logger with Warn level.

func (*Logger) WithEnabled

func (l *Logger) WithEnabled() (slog.Logger, bool)

WithEnabled returns the logger and its enabled state.

func (*Logger) WithField

func (l *Logger) WithField(label string, value any) slog.Logger

WithField implements slog.Logger.

func (*Logger) WithFields

func (l *Logger) WithFields(fields map[string]any) slog.Logger

WithFields implements slog.Logger.

func (*Logger) WithLevel

func (l *Logger) WithLevel(level slog.LogLevel) slog.Logger

WithLevel returns a logger with the specified level.

func (*Logger) WithStack

func (l *Logger) WithStack(skip int) slog.Logger

WithStack implements slog.Logger.

type Message

type Message struct {
	Fields  map[string]any
	Message string
	Level   slog.LogLevel
	Stack   bool
}

Message represents a recorded log message for testing.

func (Message) Equal added in v0.11.0

func (m Message) Equal(other Message) bool

Equal reports whether two messages carry the same level, text and stack marker, with fields settled key by key through core.AreEqual. Unlike comparing the Message.String rendering, it distinguishes values whose %v text coincides — 1 and "1" — and settles non-comparable values such as slices by content.

func (Message) String

func (m Message) String() string

String returns a string representation of the message with sorted fields.

type Recorder

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

Recorder provides thread-safe recording of log messages for testing.

func NewRecorder

func NewRecorder() *Recorder

NewRecorder creates a new message recorder for testing.

func (*Recorder) Clear

func (r *Recorder) Clear()

Clear removes all recorded messages.

func (*Recorder) GetMessages

func (r *Recorder) GetMessages() []Message

GetMessages returns a copy of all recorded messages.

func (*Recorder) Record

func (r *Recorder) Record(msg Message)

Record stores a log message in the recorder.

Jump to

Keyboard shortcuts

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