Documentation
¶
Overview ¶
Package logger provides a small Logger interface over log/slog so production code logs to stderr/JSON while tests substitute Capture to assert on emitted records.
Production:
log := logger.New(logger.Config{Format: logger.FormatJSON, Level: slog.LevelInfo})
log.Info("server started", "addr", addr)
Tests:
cap := logger.NewCapture(slog.LevelDebug)
cap.Info("hello", "k", 1)
if !cap.HasMessage("hello") { t.Fatal("missing message") }
Index ¶
- type Capture
- func (c *Capture) Debug(msg string, args ...any)
- func (c *Capture) Enabled(_ context.Context, level slog.Level) bool
- func (c *Capture) Error(msg string, args ...any)
- func (c *Capture) FilterLevel(level slog.Level) []Record
- func (c *Capture) HasMessage(substr string) bool
- func (c *Capture) Info(msg string, args ...any)
- func (c *Capture) Records() []Record
- func (c *Capture) Reset()
- func (c *Capture) Warn(msg string, args ...any)
- func (c *Capture) With(args ...any) Logger
- type Config
- type Format
- type Logger
- type Record
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Capture ¶
type Capture struct {
// contains filtered or unexported fields
}
Capture is a Logger that buffers records in memory for assertion. Safe for concurrent use.
func NewCapture ¶
NewCapture returns a Capture that records every entry at level or above.
func (*Capture) FilterLevel ¶
FilterLevel returns the subset of records at exactly level.
func (*Capture) HasMessage ¶
HasMessage reports whether any captured record's Msg contains substr.
type Config ¶
type Config struct {
// Writer receives the encoded records. Defaults to os.Stderr.
Writer io.Writer
// Format selects text vs JSON. Defaults to JSON (good for production
// log aggregators; switch to FormatText for local development).
Format Format
// Level is the minimum level recorded. Defaults to slog.LevelInfo.
Level slog.Level
// AddSource adds a source=file:line attribute to every record.
AddSource bool
}
Config controls New. The zero value writes JSON at info level to stderr.
type Logger ¶
type Logger interface {
Debug(msg string, args ...any)
Info(msg string, args ...any)
Warn(msg string, args ...any)
Error(msg string, args ...any)
// With returns a child Logger that prepends args to every record.
With(args ...any) Logger
// Enabled reports whether the underlying handler accepts records at level.
Enabled(ctx context.Context, level slog.Level) bool
}
Logger is the structured-logging interface. The methods mirror slog's shape so callers can switch implementations without rewriting call sites.
func Discard ¶
func Discard() Logger
Discard returns a Logger that drops everything. Useful for benchmarks.