/
logging.go
191 lines (158 loc) · 5.04 KB
/
logging.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
// Copyright 2021-2024 Zenauth Ltd.
// SPDX-License-Identifier: Apache-2.0
package logging
import (
"context"
"os"
"strconv"
"strings"
"time"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
"github.com/mattn/go-isatty"
"go.elastic.co/ecszap"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zapgrpc"
"google.golang.org/grpc/grpclog"
"github.com/cerbos/cerbos/internal/util"
)
const defaultTmpLogLevelDuration = 10 * time.Minute
type ctxLog struct{}
var ctxLogKey = &ctxLog{}
// InitLogging initializes the global logger.
func InitLogging(ctx context.Context, level string) {
if envLevel := os.Getenv("CERBOS_LOG_LEVEL"); envLevel != "" {
doInitLogging(ctx, envLevel)
return
}
doInitLogging(ctx, level)
}
func doInitLogging(ctx context.Context, level string) {
var logger *zap.Logger
minLogLevel := zapcore.InfoLevel
switch strings.ToUpper(level) {
case "DEBUG":
minLogLevel = zapcore.DebugLevel
case "INFO":
minLogLevel = zapcore.InfoLevel
case "WARN":
minLogLevel = zapcore.WarnLevel
case "ERROR":
minLogLevel = zapcore.ErrorLevel
default:
if strings.HasPrefix(level, "V") {
if vLevel, err := strconv.Atoi(strings.TrimPrefix(level, "V")); err == nil {
minLogLevel = zapcore.Level(-vLevel)
}
}
}
encoderConf := ecszap.NewDefaultEncoderConfig().ToZapCoreEncoderConfig()
var consoleEncoder zapcore.Encoder
if !isatty.IsTerminal(os.Stdout.Fd()) {
consoleEncoder = zapcore.NewJSONEncoder(encoderConf)
} else {
encoderConf.EncodeLevel = zapcore.CapitalColorLevelEncoder
consoleEncoder = zapcore.NewConsoleEncoder(encoderConf)
}
consoleErrors := zapcore.Lock(os.Stderr)
consoleInfo := zapcore.Lock(os.Stdout)
atomicLevel := zap.NewAtomicLevelAt(minLogLevel)
errorPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return atomicLevel.Enabled(lvl) && lvl >= zapcore.ErrorLevel
})
infoPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return atomicLevel.Enabled(lvl) && lvl < zapcore.ErrorLevel
})
core := zapcore.NewTee(
zapcore.NewCore(consoleEncoder, consoleErrors, errorPriority),
zapcore.NewCore(consoleEncoder, consoleInfo, infoPriority),
)
stackTraceEnabler := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl > zapcore.ErrorLevel
})
logger = zap.New(core, zap.AddStacktrace(stackTraceEnabler))
zap.ReplaceGlobals(logger.Named(util.AppName))
zap.RedirectStdLog(logger.Named("stdlog"))
grpclog.SetLoggerV2(zapgrpc.NewLogger(logger.Named("grpc").WithOptions(
zap.IncreaseLevel(zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl > zapcore.ErrorLevel
})))))
if minLogLevel > zap.DebugLevel {
handleUSR1Signal(ctx, minLogLevel, &atomicLevel)
}
}
// setLogLevelForDuration temporarily sets the global log level to the given level for a period of time.
func setLogLevelForDuration(ctx context.Context, doneChan chan<- struct{}, extendChan <-chan struct{}, originalLevel zapcore.Level, atomicLevel *zap.AtomicLevel) {
log := zap.S().Named("logging")
tmpLogLevelDuration := defaultTmpLogLevelDuration
if td := os.Getenv("CERBOS_TEMP_LOG_LEVEL_DURATION"); td != "" {
if d, err := time.ParseDuration(td); err == nil {
tmpLogLevelDuration = d
}
}
log.Infof("Temporarily setting global log level to %s for %s", zap.DebugLevel, tmpLogLevelDuration)
atomicLevel.SetLevel(zap.DebugLevel)
timer := time.NewTimer(tmpLogLevelDuration)
defer func() {
timer.Stop()
log.Infof("Reverting global log level to %s", originalLevel)
atomicLevel.SetLevel(originalLevel)
doneChan <- struct{}{}
}()
extendCount := 0
for {
select {
case <-ctx.Done():
return
case <-timer.C:
if extendCount <= 0 {
return
}
log.Infof("Extending %s log level for further %s", zap.DebugLevel, tmpLogLevelDuration)
extendCount--
timer.Reset(tmpLogLevelDuration)
case <-extendChan:
log.Infof("Log level will be %s for further %s", zap.DebugLevel, tmpLogLevelDuration)
extendCount++
}
}
}
// FromContext returns the logger from the context if one exists. Otherwise it returns a new logger.
func FromContext(ctx context.Context) *zap.Logger {
log, ok := ctx.Value(ctxLogKey).(*zap.Logger)
if !ok || log == nil {
return zap.L()
}
return log
}
// ToContext adds a logger to the context.
func ToContext(ctx context.Context, log *zap.Logger) context.Context {
return context.WithValue(ctx, ctxLogKey, log)
}
// ReqScopeLog returns a request-scoped logger with request fields populated.
func ReqScopeLog(ctx context.Context) *zap.Logger {
log := FromContext(ctx)
fields := GRPCLogFieldsToZap(logging.ExtractFields(ctx))
return log.With(fields...)
}
func GRPCLogFieldsToZap(fields logging.Fields) []zap.Field {
if len(fields) == 0 {
return nil
}
out := make([]zap.Field, 0, len(fields)/2) //nolint:mnd
iter := fields.Iterator()
for iter.Next() {
key, value := iter.At()
switch v := value.(type) {
case string:
out = append(out, zap.String(key, v))
case int:
out = append(out, zap.Int(key, v))
case bool:
out = append(out, zap.Bool(key, v))
default:
out = append(out, zap.Any(key, v))
}
}
return out
}