/
log.go
64 lines (53 loc) · 1.37 KB
/
log.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package logger
import (
"context"
"fmt"
"log/slog"
"os"
"path/filepath"
"runtime"
"time"
)
var jsonLogger = slog.New(slog.NewJSONHandler(
os.Stdout,
&slog.HandlerOptions{
AddSource: true,
ReplaceAttr: replace,
}))
func replace(groups []string, a slog.Attr) slog.Attr {
// Remove the directory from the source's filename.
if a.Key == slog.SourceKey {
source := a.Value.Any().(*slog.Source)
source.Function = ""
source.File = filepath.Base(source.File)
}
// format time RFC3339 in utc
if a.Key == slog.TimeKey {
a.Value = slog.StringValue(a.Value.Time().UTC().Format(time.RFC3339))
}
return a
}
func logRecord(level slog.Level, msg string) {
if !jsonLogger.Enabled(context.Background(), level) {
return
}
var pcs [1]uintptr
runtime.Callers(3, pcs[:]) // skip [Callers, logRecord, Infof/Debugf]
r := slog.NewRecord(time.Now(), level, msg, pcs[0])
_ = jsonLogger.Handler().Handle(context.Background(), r)
}
func Logger() *slog.Logger {
return jsonLogger
}
func Infof(format string, args ...any) {
logRecord(slog.LevelInfo, fmt.Sprintf(format, args...))
}
func Debugf(format string, args ...any) {
logRecord(slog.LevelDebug, fmt.Sprintf(format, args...))
}
func Errorf(format string, args ...any) {
logRecord(slog.LevelError, fmt.Sprintf(format, args...))
}
func Warnf(format string, args ...any) {
logRecord(slog.LevelWarn, fmt.Sprintf(format, args...))
}