Skip to content

Commit e53a531

Browse files
committed
add logger package
Signed-off-by: Markus Blaschke <[email protected]>
1 parent ba268e7 commit e53a531

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed

logger/logger.go

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
package logger
2+
3+
import (
4+
"context"
5+
"log/slog"
6+
)
7+
8+
const (
9+
LevelTrace = slog.Level(-8)
10+
LevelFatal = slog.Level(12)
11+
LevelPanic = slog.Level(255)
12+
)
13+
14+
var (
15+
levelNames = map[slog.Leveler]string{
16+
LevelTrace: "TRACE",
17+
LevelFatal: "FATAL",
18+
}
19+
)
20+
21+
type (
22+
Logger struct {
23+
*slog.Logger
24+
}
25+
26+
HandlerOptions struct {
27+
*slog.HandlerOptions
28+
ShowTime bool
29+
}
30+
)
31+
32+
func NewHandlerOptions(handler *slog.HandlerOptions) *HandlerOptions {
33+
if handler == nil {
34+
handler = &slog.HandlerOptions{}
35+
}
36+
37+
ret := &HandlerOptions{HandlerOptions: handler}
38+
39+
existingFunc := &handler.ReplaceAttr
40+
handler.ReplaceAttr = NewReplaceAttr(ret, existingFunc)
41+
42+
return ret
43+
}
44+
45+
func NewReplaceAttr(handler *HandlerOptions, existingFunc *func(groups []string, a slog.Attr) slog.Attr) func(groups []string, a slog.Attr) slog.Attr {
46+
return func(groups []string, a slog.Attr) slog.Attr {
47+
switch a.Key {
48+
case slog.LevelKey:
49+
level := a.Value.Any().(slog.Level)
50+
if levelLabel, exists := levelNames[level]; exists {
51+
a.Value = slog.StringValue(levelLabel)
52+
} else {
53+
a.Value = slog.StringValue(level.String())
54+
}
55+
case slog.TimeKey:
56+
if !handler.ShowTime {
57+
return slog.Attr{}
58+
}
59+
}
60+
61+
if existingFunc != nil {
62+
return (*existingFunc)(groups, a)
63+
} else {
64+
return a
65+
}
66+
}
67+
}
68+
69+
func New(handler slog.Handler) *Logger {
70+
return &Logger{
71+
Logger: slog.New(handler),
72+
}
73+
}
74+
func (l *Logger) Trace(msg string, fields ...any) {
75+
l.Log(context.Background(), LevelTrace, msg, fields...)
76+
}
77+
78+
func (l *Logger) Fatal(msg string, fields ...any) {
79+
l.Log(context.Background(), LevelFatal, msg, fields...)
80+
}
81+
82+
func (l *Logger) Panic(msg string, fields ...any) {
83+
l.Log(context.Background(), LevelPanic, msg, fields...)
84+
panic(msg)
85+
}
86+
87+
func (l *Logger) With(args ...any) *Logger {
88+
return &Logger{l.Logger.With(args...)}
89+
}
90+
91+
func (l *Logger) WithGroup(name string) *Logger {
92+
return &Logger{l.Logger.WithGroup(name)}
93+
}

0 commit comments

Comments
 (0)