-
Notifications
You must be signed in to change notification settings - Fork 0
[rlog] Updates based on integration lessons learned #39
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
b30cd96
rlog: global fatal hook, slog default sync, With/WithGroup, fan-out, …
chris-okuda 97980e7
remove old test stuff
chris-okuda 5534eda
fix bug in fanout handler
chris-okuda 449351e
note to use the slog multihandler in go 1.26 or later and return the …
chris-okuda e8ac89d
we can get rid of the atomic if I do things correctly with a pointer
chris-okuda 6f362b0
add with/withgroup test
chris-okuda File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } | ||
|
|
||
| // 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...) | ||
| } | ||
chris-okuda marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| // 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} | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
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.MultiHandlerso maybe we can use that if we upgrade?There was a problem hiding this comment.
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.