-
Notifications
You must be signed in to change notification settings - Fork 64
/
utils.go
66 lines (56 loc) · 1.46 KB
/
utils.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
package main
import (
"context"
"encoding/json"
"strings"
"github.com/rs/zerolog"
globalLogger "github.com/rs/zerolog/log"
)
var truthyStrings = map[string]struct{}{
"yes": {},
"true": {},
"1": {},
}
func isTruthy(s string) bool {
s = strings.ToLower(strings.TrimSpace(s))
_, found := truthyStrings[s]
return found
}
func prettyJSON(obj any) (string, error) {
bytes, err := json.MarshalIndent(obj, "", " ")
if err != nil {
return "", err
}
return string(bytes), nil
}
func removeDuplicates(slice []string) []string {
res := make([]string, 0, len(slice))
seen := make(map[string]struct{}, len(slice))
for _, s := range slice {
if _, found := seen[s]; !found {
res = append(res, s)
}
}
return res
}
func getLoggerWithTag(ctx context.Context, key string, value string) (context.Context, *zerolog.Logger) {
return getLoggerWithTags(ctx, map[string]string{key: value})
}
func getLoggerWithTags(ctx context.Context, tags map[string]string) (context.Context, *zerolog.Logger) {
logger := zerolog.Ctx(ctx)
if logger == nil ||
logger == zerolog.DefaultContextLogger ||
logger.GetLevel() == zerolog.Disabled {
// Use the global logger if nothing was set on the context
logger = &globalLogger.Logger
}
loggerContext := logger.With()
for key, value := range tags {
if key != "" {
loggerContext = loggerContext.Str(key, value)
}
}
extendedLogger := loggerContext.Logger()
ctx = extendedLogger.WithContext(ctx)
return ctx, &extendedLogger
}