Skip to content

Commit 34cc53a

Browse files
fix source key
1 parent 7a0b805 commit 34cc53a

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

_example/main.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"log/slog"
77
"math"
88
"os"
9+
"path/filepath"
910
"time"
1011

1112
"github.com/golang-cz/devslog"
@@ -91,6 +92,11 @@ func replaceAttr(groups []string, a slog.Attr) slog.Attr {
9192
default:
9293
a.Value = slog.StringValue("EMERGENCY")
9394
}
95+
96+
case slog.SourceKey:
97+
source := a.Value.Any().(*slog.Source)
98+
source.File = filepath.Base(source.File)
99+
return slog.Attr{}
94100
}
95101

96102
return a

devslog.go

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -181,15 +181,29 @@ func (h *developHandler) Handle(ctx context.Context, r slog.Record) error {
181181
func (h *developHandler) formatSourceInfo(b []byte, r *slog.Record) []byte {
182182
if h.opts.AddSource {
183183
f, _ := runtime.CallersFrames([]uintptr{r.PC}).Next()
184+
s := &slog.Source{
185+
Function: f.Function,
186+
File: f.File,
187+
Line: f.Line,
188+
}
189+
190+
if h.opts.ReplaceAttr != nil {
191+
attr := h.opts.ReplaceAttr([]string{}, slog.Any(slog.SourceKey, s))
192+
if attr.Key == "" {
193+
b = append(b, '\n')
194+
return b
195+
}
196+
}
197+
184198
b = append(b, h.cs([]byte("@@@"), fgBlue)...)
185199
b = append(b, ' ')
186200

187201
if h.opts.SameSourceInfoColor {
188-
b = append(b, h.ul(h.cs(append(append([]byte(f.File), ':'), []byte(strconv.Itoa(f.Line))...), fgYellow))...)
202+
b = append(b, h.ul(h.cs(append(append([]byte(s.File), ':'), []byte(strconv.Itoa(s.Line))...), fgYellow))...)
189203
} else {
190-
b = append(b, h.ul(h.cs([]byte(f.File), fgYellow))...)
204+
b = append(b, h.ul(h.cs([]byte(s.File), fgYellow))...)
191205
b = append(b, ':')
192-
b = append(b, h.cs([]byte(strconv.Itoa(f.Line)), fgRed)...)
206+
b = append(b, h.cs([]byte(strconv.Itoa(s.Line)), fgRed)...)
193207
}
194208

195209
b = append(b, '\n')

0 commit comments

Comments
 (0)