-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.go
54 lines (49 loc) · 1.23 KB
/
logger.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
package main
import (
"log/slog"
"os"
"strings"
"github.com/lmittmann/tint"
"github.com/mattn/go-isatty"
)
func newLogger(debugMode, jsonOutput bool) *slog.Logger {
w := os.Stdout
var level = new(slog.LevelVar)
level.Set(slog.LevelInfo)
var replaceFunc func(groups []string, a slog.Attr) slog.Attr = nil
if debugMode {
level.Set(slog.LevelDebug)
// add source file information
wd, err := os.Getwd()
if err != nil {
panic("unable to determine working directory")
}
replaceFunc = func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.SourceKey {
source := a.Value.Any().(*slog.Source)
// remove current working directory and only leave the relative path to the program
if file, ok := strings.CutPrefix(source.File, wd); ok {
source.File = file
}
}
return a
}
}
var handler slog.Handler
if jsonOutput {
handler = slog.NewJSONHandler(w, &slog.HandlerOptions{
Level: level,
AddSource: debugMode,
ReplaceAttr: replaceFunc,
})
} else {
textOptions := &tint.Options{
Level: level,
NoColor: !isatty.IsTerminal(w.Fd()),
AddSource: debugMode,
ReplaceAttr: replaceFunc,
}
handler = tint.NewHandler(w, textOptions)
}
return slog.New(handler)
}