generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
logger.go
101 lines (86 loc) · 1.92 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
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
package observability
import (
"fmt"
"github.com/go-logr/logr"
"github.com/TBD54566975/ftl/internal/log"
)
type logSink struct {
keyValues map[string]interface{}
logger *log.Logger
}
func NewOtelLogger(logger *log.Logger, level log.Level) logr.Logger {
sink := &logSink{
logger: logger.Scope("otel").Level(level),
}
return logr.New(sink)
}
var _ logr.LogSink = &logSink{}
func (l *logSink) Init(info logr.RuntimeInfo) {
}
func (l logSink) Enabled(level int) bool {
return otelLevelToLevel(level) >= l.logger.GetLevel()
}
func (l logSink) Info(level int, msg string, kvs ...interface{}) {
// otel uses the following mapping for level to our log.Level
// 8 = Debug
// 4 = Info
// 1 = Warning
// 0 = Error
var logLevel log.Level
switch level {
case 4:
logLevel = log.Info
case 8:
logLevel = log.Debug
case 1:
logLevel = log.Warn
case 0:
logLevel = log.Error
default:
logLevel = log.Trace
}
logMsg := msg + " "
for k, v := range l.keyValues {
logMsg += fmt.Sprintf("%s: %+v ", k, v)
}
for i := 0; i < len(kvs); i += 2 {
logMsg += fmt.Sprintf("%s: %+v ", kvs[i], kvs[i+1])
}
l.logger.Logf(logLevel, logMsg)
}
func (l logSink) Error(err error, msg string, kvs ...interface{}) {
l.logger.Errorf(err, msg, kvs...)
}
func (l logSink) WithName(name string) logr.LogSink {
return &logSink{
keyValues: l.keyValues,
logger: l.logger.Scope(name),
}
}
func (l logSink) WithValues(kvs ...interface{}) logr.LogSink {
newMap := make(map[string]interface{}, len(l.keyValues)+len(kvs)/2)
for k, v := range l.keyValues {
newMap[k] = v
}
for i := 0; i < len(kvs); i += 2 {
newMap[kvs[i].(string)] = kvs[i+1] //nolint:forcetypeassert
}
return &logSink{
keyValues: newMap,
logger: l.logger,
}
}
func otelLevelToLevel(level int) log.Level {
switch level {
case 4:
return log.Info
case 8:
return log.Debug
case 1:
return log.Warn
case 0:
return log.Error
default:
return log.Trace
}
}