Skip to content

Commit a468ce1

Browse files
committed
improve logger
Signed-off-by: Markus Blaschke <mblaschke82@gmail.com>
1 parent 22bcdab commit a468ce1

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

log/slogger/slog.go

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@ package slogger
22

33
import (
44
"context"
5+
"fmt"
56
"log/slog"
67
"os"
8+
"path/filepath"
9+
"strings"
710
)
811

912
const (
@@ -26,7 +29,10 @@ type (
2629

2730
HandlerOptions struct {
2831
*slog.HandlerOptions
29-
ShowTime bool
32+
ShowTime bool
33+
ShortenSourcePath bool
34+
35+
sourceRelPath string
3036
}
3137
)
3238

@@ -36,6 +42,9 @@ func NewHandlerOptions(handler *slog.HandlerOptions) *HandlerOptions {
3642
}
3743

3844
ret := &HandlerOptions{HandlerOptions: handler}
45+
if val, err := os.Executable(); err == nil {
46+
ret.sourceRelPath = strings.TrimRight(filepath.Dir(val), "/") + "/"
47+
}
3948

4049
if handler.ReplaceAttr != nil {
4150
handler.ReplaceAttr = NewReplaceAttr(ret, handler.ReplaceAttr)
@@ -60,6 +69,21 @@ func NewReplaceAttr(handler *HandlerOptions, callback func(groups []string, a sl
6069
if !handler.ShowTime {
6170
return slog.Attr{}
6271
}
72+
case slog.SourceKey:
73+
if handler.ShortenSourcePath {
74+
if src, ok := a.Value.Any().(*slog.Source); ok {
75+
shortPath := ""
76+
if v, ok := strings.CutPrefix(src.File, handler.sourceRelPath); ok {
77+
shortPath = v
78+
} else {
79+
fullPath := src.File
80+
seps := strings.Split(fullPath, "/")
81+
shortPath += seps[len(seps)-1]
82+
}
83+
shortPath += fmt.Sprintf(":%d", src.Line)
84+
a.Value = slog.StringValue(shortPath)
85+
}
86+
}
6387
}
6488

6589
return callback(groups, a)

0 commit comments

Comments
 (0)