forked from grafana/loki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loki.go
104 lines (90 loc) · 2.16 KB
/
loki.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
package main
import (
"bytes"
"sync"
"github.com/docker/docker/daemon/logger"
"github.com/go-kit/log"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"github.com/pao214/loki/v3/clients/pkg/logentry/stages"
"github.com/pao214/loki/v3/clients/pkg/promtail/api"
"github.com/pao214/loki/v3/clients/pkg/promtail/client"
"github.com/pao214/loki/v3/pkg/logproto"
)
var jobName = "docker"
type loki struct {
client client.Client
handler api.EntryHandler
labels model.LabelSet
logger log.Logger
closed bool
mutex sync.RWMutex
stop func()
}
// New create a new Loki logger that forward logs to Loki instance
func New(logCtx logger.Info, logger log.Logger) (logger.Logger, error) {
logger = log.With(logger, "container_id", logCtx.ContainerID)
cfg, err := parseConfig(logCtx)
if err != nil {
return nil, err
}
m := client.NewMetrics(prometheus.DefaultRegisterer, nil)
c, err := client.New(m, cfg.clientConfig, nil, logger)
if err != nil {
return nil, err
}
var handler api.EntryHandler = c
var stop = func() {}
if len(cfg.pipeline.PipelineStages) != 0 {
pipeline, err := stages.NewPipeline(logger, cfg.pipeline.PipelineStages, &jobName, prometheus.DefaultRegisterer)
if err != nil {
return nil, err
}
handler = pipeline.Wrap(c)
stop = handler.Stop
}
return &loki{
client: c,
labels: cfg.labels,
logger: logger,
handler: handler,
stop: stop,
}, nil
}
// Log implements `logger.Logger`
func (l *loki) Log(m *logger.Message) error {
l.mutex.RLock()
defer l.mutex.RUnlock()
if l.closed {
return errors.New("client closed")
}
if len(bytes.Fields(m.Line)) == 0 {
return nil
}
lbs := l.labels.Clone()
if m.Source != "" {
lbs["source"] = model.LabelValue(m.Source)
}
l.handler.Chan() <- api.Entry{
Labels: lbs,
Entry: logproto.Entry{
Timestamp: m.Timestamp,
Line: string(m.Line),
},
}
return nil
}
// Log implements `logger.Logger`
func (l *loki) Name() string {
return driverName
}
// Log implements `logger.Logger`
func (l *loki) Close() error {
l.mutex.Lock()
defer l.mutex.Unlock()
l.stop()
l.client.StopNow()
l.closed = true
return nil
}