Skip to content

Commit

Permalink
improved error dumping in attrs
Browse files Browse the repository at this point in the history
  • Loading branch information
hedzr committed Nov 1, 2024
1 parent 4f0da04 commit 123708c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 8 deletions.
6 changes: 5 additions & 1 deletion slog/attr.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ func (s Attrs) SerializeValueTo(pc *PrintCtx) {
serializeAttrs(pc, s)
}

func serializeAttrs(pc *PrintCtx, kvps Attrs) { //nolint:revive
func serializeAttrs(pc *PrintCtx, kvps Attrs) (err error) { //nolint:revive
prefix := pc.prefix
for _, v := range kvps {
if pc.noColor {
Expand Down Expand Up @@ -157,13 +157,17 @@ func serializeAttrs(pc *PrintCtx, kvps Attrs) { //nolint:revive
pc.valueStringer.WriteValue(val)
} else {
pc.appendValue(val)
if e, ok := val.(error); ok && e != nil {
err = e
}
}
pc.prefix = prefix
}

if !pc.noColor {
ct.echoResetColor(pc)
}
return
}

// type canSerializeValue interface {
Expand Down
41 changes: 34 additions & 7 deletions slog/entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -1121,14 +1121,38 @@ func (s *Entry) printImpl(ctx context.Context, pc *PrintCtx) (ret []byte) {
s.printFirstLineOfMsg(ctx, pc)
}

serializeAttrs(pc, pc.kvps)
holded := serializeAttrs(pc, pc.kvps)

if IsAnyBitsSet(Lcaller) {
s.printPC(ctx, pc)
}

s.printRestLinesOfMsg(ctx, pc)

if pc.lvl <= ErrorLevel && holded != nil && (is.DebugMode() || is.DebugBuild()) {
var stackInfo string
if _, ok := holded.(interface{ Format(s fmt.State, verb rune) }); ok {
stackInfo = fmt.Sprintf("%+v", holded)
} else {
var x Stringer
if x, ok = holded.(Stringer); ok {
stackInfo = x.String() // special for those illegal error impl like toml.DecodeError, which have no Format
} else {
stackInfo = fmt.Sprintf("%v", holded)
}
}
if pc.jsonMode {
pc.pcAppendStringKey("errDetail")
pc.pcAppendColon()
pc.pcAppendStringValue(stackInfo)
pc.pcAppendComma()
} else {
pc.pcAppendByte('\n')
txt := ct.pad(stackInfo, " ", 1)
ct.wrapColorAndBgTo(pc, red, clrLoggerNameBg, txt)
}
}

if pc.jsonMode {
pc.pcAppendByte('}')
}
Expand Down Expand Up @@ -1159,12 +1183,15 @@ func (s *Entry) printTimestamp(ctx context.Context, pc *PrintCtx) {
func (s *Entry) printLoggerName(ctx context.Context, pc *PrintCtx) {
if s.name != "" {
if pc.noColor { // json or logfmt
pc.AddString("logger", s.name)
// pc.pcAppendStringKey("logger")
// pc.pcAppendColon()
// pc.pcAppendByte('"')
// pc.pcAppendStringValue(s.name)
// pc.pcAppendByte('"')
if pc.jsonMode {
pc.pcAppendStringKey("logger")
pc.pcAppendColon()
pc.pcAppendByte('"')
pc.pcAppendStringValue(s.name)
pc.pcAppendByte('"')
} else {
pc.AddString("logger", s.name)
}
pc.pcAppendComma()
} else {
ct.wrapColorAndBgTo(pc, clrLoggerName, clrLoggerNameBg, s.name)
Expand Down

0 comments on commit 123708c

Please sign in to comment.