-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
58 lines (53 loc) · 1.3 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
55
56
57
58
package main
import (
"log/slog"
"os"
"strings"
"github.com/charmbracelet/log"
"github.com/mattn/go-isatty"
)
func newLogger(debugMode, jsonOutput bool) *slog.Logger {
w := os.Stdout
level := new(slog.LevelVar)
level.Set(slog.LevelInfo)
var replaceFunc func(groups []string, a slog.Attr) slog.Attr
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(_ []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
slogHandlerOpts := &slog.HandlerOptions{
Level: level,
AddSource: debugMode,
ReplaceAttr: replaceFunc,
}
if jsonOutput {
handler = slog.NewJSONHandler(w, slogHandlerOpts)
} else if !isatty.IsTerminal(w.Fd()) {
handler = slog.NewTextHandler(w, slogHandlerOpts)
} else {
l := log.InfoLevel
if debugMode {
l = log.DebugLevel
}
handler = log.NewWithOptions(w, log.Options{
Level: l,
ReportCaller: debugMode,
})
}
return slog.New(handler)
}