Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 49 additions & 48 deletions rlog/README.md
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
# rlog

The `r` is for “Rotational”!
The `r` is for “Rotational”! This package extends [`log/slog`](https://pkg.go.dev/log/slog) with **Trace**, **Fatal**, and **Panic**, and helpers in the usual shapes (key/value, `*Context`, `*Attrs`). See [`go doc`](https://pkg.go.dev/go.rtnl.ai/x/rlog) for the full API.

## Features Overview
- **Fatal** runs [`SetFatalHook`](https://pkg.go.dev/go.rtnl.ai/x/rlog#SetFatalHook) after logging if set; otherwise [`os.Exit(1)`](https://pkg.go.dev/os#Exit). **Panic** logs then panics with the message.
- [`MergeWithCustomLevels`](https://pkg.go.dev/go.rtnl.ai/x/rlog#MergeWithCustomLevels) maps custom levels to names `TRACE`, `FATAL`, `PANIC` in JSON/text output. [`ReplaceLevelKey`](https://pkg.go.dev/go.rtnl.ai/x/rlog#ReplaceLevelKey) does only the level mapping if you compose `ReplaceAttr` yourself. [`WithGlobalLevel`](https://pkg.go.dev/go.rtnl.ai/x/rlog#WithGlobalLevel) helps keep the global logging level synced.
- [`Logger.With`](https://pkg.go.dev/go.rtnl.ai/x/rlog#Logger.With) / [`WithGroup`](https://pkg.go.dev/go.rtnl.ai/x/rlog#Logger.WithGroup) keep a `*rlog.Logger` (same args as [`slog.Logger.With`](https://pkg.go.dev/log/slog#Logger.With)). Package-level [`With`](https://pkg.go.dev/go.rtnl.ai/x/rlog#With), [`WithGroup`](https://pkg.go.dev/go.rtnl.ai/x/rlog#WithGroup), [`Log`](https://pkg.go.dev/go.rtnl.ai/x/rlog#Log), and [`LogAttrs`](https://pkg.go.dev/go.rtnl.ai/x/rlog#LogAttrs) use the default logger.
- [`NewFanOut`](https://pkg.go.dev/go.rtnl.ai/x/rlog#NewFanOut) returns a [`slog.Handler`](https://pkg.go.dev/log/slog#Handler) that forwards each record to every child handler (multi-sink logging).
- [`NewCapturingTestHandler`](https://pkg.go.dev/go.rtnl.ai/x/rlog#NewCapturingTestHandler) helps tests capture records and JSON lines; pass `nil` or a [`testing.TB`](https://pkg.go.dev/testing#TB) to print test logs to the console. Helpers include [`ParseJSONLine`](https://pkg.go.dev/go.rtnl.ai/x/rlog#ParseJSONLine), [`ResultMaps`](https://pkg.go.dev/go.rtnl.ai/x/rlog#CapturingTestHandler.ResultMaps), and [`RecordsAndLines`](https://pkg.go.dev/go.rtnl.ai/x/rlog#CapturingTestHandler.RecordsAndLines) which returns a mutex-locked snapshot of current logs.
- [`LevelDecoder`](https://pkg.go.dev/go.rtnl.ai/x/rlog#LevelDecoder) parses level strings, including the added `TRACE`, `FATAL`, and `PANIC`.

- Wraps [`log/slog`](https://pkg.go.dev/log/slog) with extra severities **Trace** (more verbose than Debug), **Fatal**, and **Panic**, plus helpers in the usual slog shapes: key/value, `*Context`, and `*Attrs` ([`slog.LogAttrs`](https://pkg.go.dev/log/slog#LogAttrs)).
- **Fatal** logs, then runs an exit hook (default `os.Exit(1)`); **Panic** logs, then `panic`s with the message.
- Use `rlog.MergeWithCustomLevels` on handler options so JSON/text output uses level names `TRACE`, `FATAL`, and `PANIC` instead of numeric offsets.
## Default logger and Custom Handlers

## Global logger

- The default global logger will log JSON to stdout at level **Info**
- `SetDefault` replaces the global logger; `Default` returns the current one. Package-level helpers (`rlog.Info`, `rlog.Trace`, `rlog.DebugContext`, …) delegate to the global logger.
- `SetLevel`, `Level`, and `LevelString` read or update the shared [`slog.LevelVar`](https://pkg.go.dev/log/slog#LevelVar) used by the default install.
- `WithGlobalLevel` sets `HandlerOptions.Level` to that same `LevelVar`. Use `MergeWithCustomLevels(WithGlobalLevel(opts))` when creating handlers so `SetLevel` still controls verbosity after `SetDefault`. A fixed `HandlerOptions{Level: …}` does not follow `SetLevel`.
- The package default logs JSON to stdout at **Info**.
- [`SetDefault`](https://pkg.go.dev/go.rtnl.ai/x/rlog#SetDefault) replaces rlog’s global logger and updates [`slog.Default`](https://pkg.go.dev/log/slog#Default) via [`slog.SetDefault`](https://pkg.go.dev/log/slog#SetDefault).
- [`SetLevel`](https://pkg.go.dev/go.rtnl.ai/x/rlog#SetLevel), [`Level`](https://pkg.go.dev/go.rtnl.ai/x/rlog#Level), and [`LevelString`](https://pkg.go.dev/go.rtnl.ai/x/rlog#LevelString) read or set the shared [`slog.LevelVar`](https://pkg.go.dev/log/slog#LevelVar) wired into the default install.
- Handlers you build yourself should use `MergeWithCustomLevels(WithGlobalLevel(opts))` so they still honor that threshold after you call [`SetDefault`](https://pkg.go.dev/go.rtnl.ai/x/rlog#SetDefault); see [`WithGlobalLevel`](https://pkg.go.dev/go.rtnl.ai/x/rlog#WithGlobalLevel).

## Example

Below is an example program that exercises the main features of rlog.

```go
package main

Expand All @@ -31,51 +30,53 @@ import (
)

func main() {
// --- Global default (before SetDefault): shared LevelVar + package-level helpers ---
// Global default logger (JSON stdout): allow Trace.
rlog.SetLevel(rlog.LevelTrace)
rlog.Info("installed JSON default at init")
// Output: {"time":"","level":"INFO","msg":"installed JSON default at init"}
rlog.Trace("package-level Trace")
// Output: {"time":"…","level":"TRACE","msg":"package-level Trace"}
rlog.Info("hello")
// Output example: {"time":"2026-03-25T12:00:00.000-00:00","level":"INFO","msg":"hello"}
rlog.Trace("verbose")
// Output example: {"time":"…","level":"TRACE","msg":"verbose"}

// --- Build a logger and use *Logger methods (handler uses global LevelVar via WithGlobalLevel) ---
// Custom logger: MergeWithCustomLevels names TRACE/FATAL/PANIC; WithGlobalLevel ties
// level to rlog.SetLevel so this handler follows the same threshold as the default.
opts := rlog.MergeWithCustomLevels(rlog.WithGlobalLevel(nil))
h := slog.NewJSONHandler(os.Stdout, opts)
log := rlog.New(slog.New(h))
log.SetExitFunc(func() {}) // omit in production; avoids exit in this demo

ctx := context.Background()
log := rlog.New(slog.New(slog.NewJSONHandler(os.Stdout, opts)))

// Rlog-added level: key/value (Trace, Fatal, Panic have *Context and *Attrs too)
// rlog-only level + key/value fields (Trace also has TraceContext, TraceAttrs, …).
log.Trace("trace-msg", "k", "v")
// Output: {"time":"…","level":"TRACE","msg":"trace-msg","k":"v"}
// Output example: {"time":"…","level":"TRACE","msg":"trace-msg","k":"v"}

// Standard slog level + context (same idea for InfoContext, WarnContext, …)
log.DebugContext(ctx, "debug-msg", "k", "v")
// Output: {"time":"…","level":"DEBUG","msg":"debug-msg","k":"v"}

// Standard slog level + slog.Attr (LogAttrs-style; same for WarnAttrs, ErrorAttrs, …)
log.InfoAttrs(ctx, "info-msg", slog.String("k", "v"))
// Output: {"time":"…","level":"INFO","msg":"info-msg","k":"v"}

log.Fatal("fatal-msg") // would os.Exit(1) without SetExitFunc
// Output: {"time":"…","level":"FATAL","msg":"fatal-msg"}
// Without a hook, Fatal would os.Exit(1) and the rest of main would not run.
rlog.SetFatalHook(func() {}) // demo only — replace with test hook or omit in production
defer rlog.SetFatalHook(nil) // setting the fatal hook to nil causes future Fatal calls to use os.Exit(1)
log.Fatal("fatal-msg")
// Output example: {"time":"…","level":"FATAL","msg":"fatal-msg"} — then runs the fatal hook (no exit here)

// Panic levels call panic("panic-msg") after logging
func() {
defer func() { recover() }()
log.Panic("panic-msg") // logs then panic(message)
// Output: {"time":"…","level":"PANIC","msg":"panic-msg"}
log.Panic("panic-msg")
// Output example: {"time":"…","level":"PANIC","msg":"panic-msg"} — then panic("panic-msg")
}()

// --- Point package-level API at this logger ---
rlog.SetDefault(log)
rlog.Default().Warn("same logger as SetDefault")
// Output: {"time":"…","level":"WARN","msg":"same logger as SetDefault"}
rlog.DebugContext(ctx, "same logger via package-level DebugContext")
// Output: {"time":"…","level":"DEBUG","msg":"same logger via package-level DebugContext"}
rlog.InfoAttrs(ctx, "same logger via package-level InfoAttrs", slog.String("k", "v"))
// Output: {"time":"…","level":"INFO","msg":"same logger via package-level InfoAttrs","k":"v"}
// WithGroup/With return *rlog.Logger and work the same as for a slog.Logger.
sub := log.WithGroup("svc").With("name", "api")
sub.Info("scoped")
// Output example: {"time":"…","level":"INFO","msg":"scoped","svc":{"name":"api"}}

// Stdlib-style context and slog.Attr APIs on *rlog.Logger.
log.DebugContext(context.Background(), "debug-msg", "k", "v")
// Output example: {"time":"…","level":"DEBUG","msg":"debug-msg","k":"v"}
log.InfoAttrs(context.Background(), "info-msg", slog.String("k", "v"))
// Output example: {"time":"…","level":"INFO","msg":"info-msg","k":"v"}


// Package-level helpers and slog.Default now use this logger.
new := log.With(slog.String("new", "logger"))
rlog.SetDefault(new)
rlog.Warn("via package after SetDefault")
// Output example: {"time":"…","level":"WARN","msg":"via package after SetDefault","new":"logger"}
rlog.FatalAttrs("fatal-msg", slog.String("fatal", "attr"))
// Output example: {"time":"…","level":"FATAL","msg":"fatal-msg","new":"logger","fatal":"attr"} — then runs the fatal hook (no exit here)
}
```

JSON output uses the default JSON handler’s `time` field; levels show as `TRACE`, `DEBUG`, `INFO`, etc.
68 changes: 68 additions & 0 deletions rlog/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// Package rlog wraps [log/slog] with extra levels (Trace, Fatal, Panic), test
// capture helpers, and small slog utilities (handler options, global level sync,
// multi-sink fan-out). See [README.md in the repo], or [rlog on pkg.go.dev], for
// API summary and usage notes.
//
// package main
//
// import (
// "context"
// "log/slog"
// "os"
//
// "go.rtnl.ai/x/rlog"
// )
//
// func main() {
// // Global default logger (JSON stdout): allow Trace.
// rlog.SetLevel(rlog.LevelTrace)
// rlog.Info("hello")
// // Output example: {"time":"2026-03-25T12:00:00.000-00:00","level":"INFO","msg":"hello"}
// rlog.Trace("verbose")
// // Output example: {"time":"…","level":"TRACE","msg":"verbose"}
//
// // Custom logger: MergeWithCustomLevels names TRACE/FATAL/PANIC; WithGlobalLevel ties
// // level to rlog.SetLevel so this handler follows the same threshold as the default.
// opts := rlog.MergeWithCustomLevels(rlog.WithGlobalLevel(nil))
// log := rlog.New(slog.New(slog.NewJSONHandler(os.Stdout, opts)))
//
// // rlog-only level + key/value fields (Trace also has TraceContext, TraceAttrs, …).
// log.Trace("trace-msg", "k", "v")
// // Output example: {"time":"…","level":"TRACE","msg":"trace-msg","k":"v"}
//
// // Without a hook, Fatal would os.Exit(1) and the rest of main would not run.
// rlog.SetFatalHook(func() {}) // demo only — replace with test hook or omit in production
// defer rlog.SetFatalHook(nil) // setting the fatal hook to nil causes future Fatal calls to use os.Exit(1)
// log.Fatal("fatal-msg")
// // Output example: {"time":"…","level":"FATAL","msg":"fatal-msg"} — then runs the fatal hook (no exit here)
//
// // Panic levels call panic("panic-msg") after logging
// func() {
// defer func() { recover() }()
// log.Panic("panic-msg")
// // Output example: {"time":"…","level":"PANIC","msg":"panic-msg"} — then panic("panic-msg")
// }()
//
// // WithGroup/With return *rlog.Logger and work the same as for a slog.Logger.
// sub := log.WithGroup("svc").With("name", "api")
// sub.Info("scoped")
// // Output example: {"time":"…","level":"INFO","msg":"scoped","svc":{"name":"api"}}
//
// // Stdlib-style context and slog.Attr APIs on *rlog.Logger.
// log.DebugContext(context.Background(), "debug-msg", "k", "v")
// // Output example: {"time":"…","level":"DEBUG","msg":"debug-msg","k":"v"}
// log.InfoAttrs(context.Background(), "info-msg", slog.String("k", "v"))
// // Output example: {"time":"…","level":"INFO","msg":"info-msg","k":"v"}
//
// // Package-level helpers and slog.Default now use this logger.
// new := log.With(slog.String("new", "logger"))
// rlog.SetDefault(new)
// rlog.Warn("via package after SetDefault")
// // Output example: {"time":"…","level":"WARN","msg":"via package after SetDefault","new":"logger"}
// rlog.FatalAttrs("fatal-msg", slog.String("fatal", "attr"))
// // Output example: {"time":"…","level":"FATAL","msg":"fatal-msg","new":"logger","fatal":"attr"} — then runs the fatal hook (no exit here)
// }
//
// [README.md in the repo]: https://github.com/rotationalio/x/blob/main/rlog/README.md
// [rlog on pkg.go.dev]: https://pkg.go.dev/go.rtnl.ai/x/rlog
package rlog
84 changes: 84 additions & 0 deletions rlog/fanout.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package rlog

import (
"context"
"errors"
"log/slog"
)

// FanOut is a [slog.Handler] that forwards each record to every child handler,
// using a fresh [slog.Record.Clone] per child. For Go 1.26 or later, use the
// standard library's [slog.MultiHandler] instead; this is a clone of the
// functionality for Go 1.25 and earlier.
type FanOut struct {
handlers []slog.Handler
}
Comment on lines +9 to +15
Copy link
Copy Markdown
Contributor Author

@chris-okuda chris-okuda Mar 26, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We were going to need this for Quarterdeck and other stuff. I also didn't realize G0 1.26 provides a slog.MultiHandler so maybe we can use that if we upgrade?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh interesting - yes, I'm happy to upgrade to 1.26 if that makes our lives easier.


// NewFanOut returns a new [FanOut] that forwards each record to every child
// handler. For Go 1.26 or later, use [slog.MultiHandler] instead; this is a
// clone of the functionality for Go 1.25 and earlier.
func NewFanOut(handlers ...slog.Handler) *FanOut {
hs := append([]slog.Handler(nil), handlers...)
return &FanOut{handlers: hs}
}

// Enabled reports whether any child handler accepts the given level.
func (f *FanOut) Enabled(ctx context.Context, level slog.Level) bool {
for _, h := range f.handlers {
if h.Enabled(ctx, level) {
return true
}
}
return false
}

// Handle forwards a clone of r to each child that [slog.Handler.Enabled] accepts
// for r's level, and joins any non-nil errors.
func (f *FanOut) Handle(ctx context.Context, r slog.Record) error {
if len(f.handlers) == 0 {
return nil
}

level := r.Level
var errs []error
for _, h := range f.handlers {
if h.Enabled(ctx, level) {
r2 := r.Clone()
if err := h.Handle(ctx, r2); err != nil {
errs = append(errs, err)
}
}
}

return errors.Join(errs...)
}

// WithAttrs returns a [FanOut] whose children are wrapped with the same attrs.
func (f *FanOut) WithAttrs(attrs []slog.Attr) slog.Handler {
if len(attrs) == 0 {
return f
}

n := len(f.handlers)
next := make([]slog.Handler, n)
for i, h := range f.handlers {
next[i] = h.WithAttrs(attrs)
}

return &FanOut{handlers: next}
}

// WithGroup returns a [FanOut] whose children are wrapped with the same group.
func (f *FanOut) WithGroup(name string) slog.Handler {
if name == "" {
return f
}

n := len(f.handlers)
next := make([]slog.Handler, n)
for i, h := range f.handlers {
next[i] = h.WithGroup(name)
}

return &FanOut{handlers: next}
}
95 changes: 95 additions & 0 deletions rlog/fanout_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package rlog_test

import (
"bytes"
"context"
"log/slog"
"strings"
"testing"
"testing/slogtest"
"time"

"go.rtnl.ai/x/assert"
"go.rtnl.ai/x/rlog"
)

// Each sink receives the same logical record when levels allow.
func TestFanOut_Handle_clonesToEachSink(t *testing.T) {
var a, b bytes.Buffer
ha := slog.NewJSONHandler(&a, rlog.MergeWithCustomLevels(&slog.HandlerOptions{Level: slog.LevelInfo}))
hb := slog.NewJSONHandler(&b, rlog.MergeWithCustomLevels(&slog.HandlerOptions{Level: slog.LevelInfo}))
f := rlog.NewFanOut(ha, hb)

ctx := context.Background()
r := slog.NewRecord(time.Now(), slog.LevelInfo, "hello", 0)
assert.Ok(t, f.Handle(ctx, r))

assert.Contains(t, a.String(), "hello")
assert.Contains(t, b.String(), "hello")
}

// Enabled is true if any child is enabled for the level.
func TestFanOut_Enabled_OR(t *testing.T) {
var quiet, loud bytes.Buffer
hQuiet := slog.NewJSONHandler(&quiet, &slog.HandlerOptions{Level: slog.LevelError})
hLoud := slog.NewJSONHandler(&loud, &slog.HandlerOptions{Level: slog.LevelDebug})
f := rlog.NewFanOut(hQuiet, hLoud)
ctx := context.Background()

assert.True(t, f.Enabled(ctx, slog.LevelInfo), "loud child accepts Info")
assert.False(t, f.Enabled(ctx, rlog.LevelTrace), "neither accepts Trace by default opts")
}

// Handle skips children whose minimum level is above the record (like slog.MultiHandler).
func TestFanOut_Handle_skipsDisabledChildren(t *testing.T) {
var quiet, loud bytes.Buffer
hQuiet := slog.NewJSONHandler(&quiet, &slog.HandlerOptions{Level: slog.LevelError})
hLoud := slog.NewJSONHandler(&loud, &slog.HandlerOptions{Level: slog.LevelDebug})
f := rlog.NewFanOut(hQuiet, hLoud)

ctx := context.Background()
r := slog.NewRecord(time.Now(), slog.LevelInfo, "hello", 0)
assert.Ok(t, f.Handle(ctx, r))

assert.Equal(t, "", strings.TrimSpace(quiet.String()), "Error-only sink must not receive Info")
assert.Contains(t, loud.String(), "hello")
}

// WithGroup on the fan-out applies to every child.
func TestFanOut_WithGroup_propagates(t *testing.T) {
var a, b bytes.Buffer
ha := slog.NewJSONHandler(&a, rlog.MergeWithCustomLevels(&slog.HandlerOptions{Level: slog.LevelInfo}))
hb := slog.NewJSONHandler(&b, rlog.MergeWithCustomLevels(&slog.HandlerOptions{Level: slog.LevelInfo}))
f := rlog.NewFanOut(ha, hb).WithGroup("outer").(*rlog.FanOut)

ctx := context.Background()
r := slog.NewRecord(time.Now(), slog.LevelInfo, "msg", 0)
r.AddAttrs(slog.String("k", "v"))
assert.Ok(t, f.Handle(ctx, r))

for _, out := range []string{a.String(), b.String()} {
assert.Contains(t, out, `"outer":`)
assert.Contains(t, out, `"k":"v"`)
}
}

// Single-child fan-out should satisfy slog's handler test suite.
func TestFanOut_slogtest_singleChild(t *testing.T) {
var buf bytes.Buffer
h := slog.NewJSONHandler(&buf, &slog.HandlerOptions{Level: slog.LevelInfo})
fan := rlog.NewFanOut(h)

err := slogtest.TestHandler(fan, func() []map[string]any {
var maps []map[string]any
for _, line := range strings.Split(strings.TrimSpace(buf.String()), "\n") {
if line == "" {
continue
}
m, e := rlog.ParseJSONLine(line)
assert.Ok(t, e)
maps = append(maps, m)
}
return maps
})
assert.Ok(t, err)
}
Loading
Loading