Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/flow/logging/logger.go
4094 views
1
package logging
2
3
import (
4
"io"
5
6
"github.com/go-kit/log"
7
)
8
9
// Logger is a logger for Grafana Agent Flow components and controllers. It
10
// implements the [log.Logger] interface.
11
type Logger struct {
12
sink *Sink
13
14
parentComponentID string
15
componentID string
16
17
orig log.Logger // Original logger before the component name was added.
18
log log.Logger // Logger with component name injected.
19
}
20
21
// New creates a new Logger from the provided logging Sink.
22
func New(sink *Sink, opts ...LoggerOption) *Logger {
23
if sink == nil {
24
sink, _ = WriterSink(io.Discard, DefaultSinkOptions)
25
}
26
27
l := &Logger{
28
sink: sink,
29
parentComponentID: sink.parentComponentID,
30
orig: sink.logger,
31
}
32
for _, opt := range opts {
33
opt(l)
34
}
35
36
// Build the final logger.
37
l.log = wrapWithComponentID(sink.logger, sink.parentComponentID, l.componentID)
38
39
return l
40
}
41
42
// LoggerOption is passed to New to customize the constructed Logger.
43
type LoggerOption func(*Logger)
44
45
// WithComponentID provides a component ID to the Logger.
46
func WithComponentID(id string) LoggerOption {
47
return func(l *Logger) {
48
l.componentID = id
49
}
50
}
51
52
// Log implements log.Logger.
53
func (c *Logger) Log(kvps ...interface{}) error {
54
return c.log.Log(kvps...)
55
}
56
57
func wrapWithComponentID(l log.Logger, parentID, componentID string) log.Logger {
58
id := fullID(parentID, componentID)
59
if id == "" {
60
return l
61
}
62
return log.With(l, "component", id)
63
}
64
65
func fullID(parentID, componentID string) string {
66
switch {
67
case componentID == "":
68
return parentID
69
case parentID == "":
70
return componentID
71
default:
72
return parentID + "/" + componentID
73
}
74
}
75
76