Skip to content
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

Implement slog.LogValuer #129

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/cockroachdb/errors

go 1.19
go 1.21

require (
github.com/cockroachdb/datadriven v1.0.2
Expand Down
32 changes: 32 additions & 0 deletions withstack/withstack.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ package withstack

import (
"fmt"
"log/slog"
"runtime"

"github.com/cockroachdb/errors/errbase"
)
Expand Down Expand Up @@ -65,6 +67,36 @@ func (w *withStack) Error() string { return w.cause.Error() }
func (w *withStack) Cause() error { return w.cause }
func (w *withStack) Unwrap() error { return w.cause }

func (w *withStack) LogValue() slog.Value {
genTraces := func(frames errbase.StackTrace) []slog.Attr {
var attrs []slog.Attr
for _, frame := range frames {
// copied logic from pkg/errors
// https://github.com/pkg/errors/blob/master/stack.go#L23-L50
ptr := uintptr(frame) - 1
var file, name string
var line int
fn := runtime.FuncForPC(ptr)
if fn == nil {
file = "unknown"
}
file, line = fn.FileLine(ptr)
name = fn.Name()
attrs = append(attrs, slog.Group(
name,
slog.String("file", file),
slog.String("name", name),
slog.Int("line", line),
))
}
return attrs
}
return slog.GroupValue(
slog.String("message", w.cause.Error()),
slog.Any("stacktrace", genTraces(w.StackTrace())),
)
}

// Format implements the fmt.Formatter interface.
func (w *withStack) Format(s fmt.State, verb rune) { errbase.FormatError(w, s, verb) }

Expand Down