forked from entrepreneur-interet-general/opensignauxfaibles
-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.go
68 lines (59 loc) · 1.44 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
59
60
61
62
63
64
65
66
67
68
package main
import (
"errors"
"log/slog"
"os"
"runtime/debug"
"strings"
"github.com/spf13/viper"
)
var loglevel *slog.LevelVar
func initLogger() {
loglevel = new(slog.LevelVar)
loglevel.Set(slog.LevelInfo)
handler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: loglevel,
//AddSource: true,
})
parentLogger := slog.New(handler)
buildInfo, _ := debug.ReadBuildInfo()
sha1 := GitCommit
appLogger := parentLogger.With(
slog.Group("app", slog.String("sha1", sha1)),
)
slog.SetDefault(appLogger)
level, err := parseLogLevel(viper.GetString("log.level"))
if err != nil {
slog.Warn("erreur de log level", slog.Any("error", err))
}
loglevel.Set(level)
slog.Info(
"initialisation",
slog.String("go", buildInfo.GoVersion),
slog.String("path", buildInfo.Path),
slog.Any("any", buildInfo.Settings),
slog.Any("level", loglevel),
)
}
func parseLogLevel(logLevel string) (slog.Level, error) {
switch strings.ToUpper(logLevel) {
case "DEBUG":
return slog.LevelDebug, nil
case "INFO":
return slog.LevelInfo, nil
case "WARN":
return slog.LevelWarn, nil
case "ERROR":
return slog.LevelError, nil
default:
return slog.LevelInfo, errors.New("log level inconnu : '" + logLevel + "'")
}
}
func ConfigureLogLevel(logLevel string) {
var level, err = parseLogLevel(logLevel)
if err != nil {
slog.Warn("Erreur de configuration sur le loglevel", slog.String("cause", err.Error()))
return
}
loglevel.Set(level)
}