Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/flow/logging/sink.go
4094 views
1
package logging
2
3
import (
4
"fmt"
5
"io"
6
"reflect"
7
8
"github.com/go-kit/log"
9
"github.com/go-kit/log/level"
10
)
11
12
// Sink is where a Controller logger will send log lines to.
13
type Sink struct {
14
w io.Writer // Raw writer to use
15
updatable bool // Whether the sink supports being updated.
16
17
// parentComponentID is the ID of the parent component which generated the
18
// sink. Empty if the sink is not associated with a component.
19
parentComponentID string
20
21
logger *lazyLogger // Constructed logger to use.
22
opts SinkOptions
23
}
24
25
// WriterSink forwards logs to the provided [io.Writer]. WriterSinks support
26
// being updated.
27
func WriterSink(w io.Writer, o SinkOptions) (*Sink, error) {
28
if w == nil {
29
w = io.Discard
30
}
31
32
l, err := writerSinkLogger(w, o)
33
if err != nil {
34
return nil, err
35
}
36
37
return &Sink{
38
w: w,
39
updatable: true,
40
41
logger: &lazyLogger{inner: l},
42
opts: o,
43
}, nil
44
}
45
46
// LoggerSink forwards logs to the provided Logger. The component ID from the
47
// provided Logger will be propagated to any new Loggers created using this
48
// Sink. LoggerSink does not support being updated.
49
func LoggerSink(c *Logger) *Sink {
50
return &Sink{
51
parentComponentID: fullID(c.parentComponentID, c.componentID),
52
53
w: io.Discard,
54
logger: &lazyLogger{inner: c.orig},
55
}
56
}
57
58
// Update reconfigures the options used for the Sink. Update will return an
59
// error if the options are invalid or if the Sink doesn't support being given
60
// SinkOptions.
61
func (s *Sink) Update(o SinkOptions) error {
62
if !s.updatable {
63
return fmt.Errorf("logging options cannot be updated in this context")
64
}
65
66
// Nothing to do if the options didn't change
67
if reflect.DeepEqual(s.opts, o) {
68
return nil
69
}
70
71
s.opts = o
72
l, err := writerSinkLogger(s.w, s.opts)
73
if err != nil {
74
return err
75
}
76
77
s.logger.UpdateInner(l)
78
return nil
79
}
80
81
func writerSinkLogger(w io.Writer, o SinkOptions) (log.Logger, error) {
82
var l log.Logger
83
84
switch o.Format {
85
case FormatLogfmt:
86
l = log.NewLogfmtLogger(log.NewSyncWriter(w))
87
case FormatJSON:
88
l = log.NewJSONLogger(log.NewSyncWriter(w))
89
default:
90
return nil, fmt.Errorf("unrecognized log format %q", o.Format)
91
}
92
93
l = level.NewFilter(l, o.Level.Filter())
94
95
if o.IncludeTimestamps {
96
l = log.With(l, "ts", log.DefaultTimestampUTC)
97
}
98
return l, nil
99
}
100
101