-
Notifications
You must be signed in to change notification settings - Fork 2
/
log.go
42 lines (35 loc) · 960 Bytes
/
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
package main
import (
"context"
"io"
"log/slog"
"os"
"strconv"
)
// buildLogger constructs a new instance of the logger
func buildLogger() *slog.Logger {
logLevel := getLogLevel()
handler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: logLevel,
})
return slog.New(handler)
}
// getLogLevel fetches the log level from the appropriate environment variable
func getLogLevel() slog.Level {
env := os.Getenv(EnvLogLevel)
level, err := strconv.Atoi(env)
if err != nil {
return slog.LevelError
}
return slog.Level(level)
}
func setLoggerIntoContext(ctx context.Context, logger *slog.Logger) context.Context {
return context.WithValue(ctx, ContextKeyLogger, logger)
}
func getLoggerFromContext(ctx context.Context) *slog.Logger {
if l, ok := ctx.Value(ContextKeyLogger).(*slog.Logger); ok && l != nil {
return l
}
// return a discard all logger
return slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{}))
}