Skip to content

Commit

Permalink
slogutil: export PrintRecovered
Browse files Browse the repository at this point in the history
  • Loading branch information
ainar-g committed Feb 27, 2025
1 parent 5975724 commit bf60a8f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 13 deletions.
24 changes: 11 additions & 13 deletions logutil/slogutil/defer.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,7 @@ func CloseAndLog(ctx context.Context, l *slog.Logger, closer io.Closer, lvl slog
// RecoverAndLog is a deferred helper that recovers from a panic and logs the
// panic value into l along with the stacktrace. l must not be nil.
func RecoverAndLog(ctx context.Context, l *slog.Logger) {
v := recover()
if v != nil {
printRecovered(ctx, l, v)
}
PrintRecovered(ctx, l, recover())
}

// RecoverAndLogDefault is like [RecoverAndLog] but tries to get the logger from
Expand All @@ -57,24 +54,25 @@ func RecoverAndLogDefault(ctx context.Context) {
l = slog.Default()
}

printRecovered(ctx, l, v)
PrintRecovered(ctx, l, v)
}

// RecoverAndExit recovers a panic, logs it using l, and then exits with the
// given exit code. l must not be nil.
func RecoverAndExit(ctx context.Context, l *slog.Logger, code osutil.ExitCode) {
v := recover()
if v == nil {
return
}

printRecovered(ctx, l, v)
PrintRecovered(ctx, l, recover())

os.Exit(code)
}

// printRecovered prints the recovered value. l must not be nil.
func printRecovered(ctx context.Context, l *slog.Logger, v any) {
// PrintRecovered prints a message with the recovered value, if there is any, as
// well as the stack. If v is nil, PrintRecovered does nothing. Otherwise, l
// must not be nil.
func PrintRecovered(ctx context.Context, l *slog.Logger, v any) {
if v == nil {
return
}

var args []any
if err, ok := v.(error); ok {
args = []any{KeyError, err}
Expand Down
27 changes: 27 additions & 0 deletions logutil/slogutil/defer_example_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package slogutil_test

import (
"bytes"
"context"
"fmt"
"log/slog"
"strings"

"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/logutil/slogutil"
Expand Down Expand Up @@ -53,3 +55,28 @@ func ExampleCloseAndLog() {
// actual closer with error:
// DEBUG deferred closing err="close failed"
}

func ExamplePrintRecovered() {
ctx := context.Background()

output := &bytes.Buffer{}
l := slogutil.New(&slogutil.Config{
Output: output,
})

func() {
defer func() { slogutil.PrintRecovered(ctx, l, recover()) }()

l = l.With("extra", "parameters", "added", "later")

panic("test value")
}()

// Only print the first line, since the stack trace is not reproducible in
// examples.
lines := strings.Split(output.String(), "\n")
fmt.Println(lines[0])

// Output:
// ERROR recovered from panic extra=parameters added=later value="test value"
}

0 comments on commit bf60a8f

Please sign in to comment.