-
Notifications
You must be signed in to change notification settings - Fork 485
/
logger.go
74 lines (60 loc) · 1.6 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
package logging
import (
"io"
"github.com/go-kit/log"
)
// Logger is a logger for Grafana Agent Flow components and controllers. It
// implements the [log.Logger] interface.
type Logger struct {
sink *Sink
parentComponentID string
componentID string
orig log.Logger // Original logger before the component name was added.
log log.Logger // Logger with component name injected.
}
// New creates a new Logger from the provided logging Sink.
func New(sink *Sink, opts ...LoggerOption) *Logger {
if sink == nil {
sink, _ = WriterSink(io.Discard, DefaultSinkOptions)
}
l := &Logger{
sink: sink,
parentComponentID: sink.parentComponentID,
orig: sink.logger,
}
for _, opt := range opts {
opt(l)
}
// Build the final logger.
l.log = wrapWithComponentID(sink.logger, sink.parentComponentID, l.componentID)
return l
}
// LoggerOption is passed to New to customize the constructed Logger.
type LoggerOption func(*Logger)
// WithComponentID provides a component ID to the Logger.
func WithComponentID(id string) LoggerOption {
return func(l *Logger) {
l.componentID = id
}
}
// Log implements log.Logger.
func (c *Logger) Log(kvps ...interface{}) error {
return c.log.Log(kvps...)
}
func wrapWithComponentID(l log.Logger, parentID, componentID string) log.Logger {
id := fullID(parentID, componentID)
if id == "" {
return l
}
return log.With(l, "component", id)
}
func fullID(parentID, componentID string) string {
switch {
case componentID == "":
return parentID
case parentID == "":
return componentID
default:
return parentID + "/" + componentID
}
}