forked from grafana/loki
/
metrics.go
306 lines (271 loc) · 10.8 KB
/
metrics.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package logql
import (
"context"
"strings"
"time"
"github.com/dustin/go-humanize"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
promql_parser "github.com/prometheus/prometheus/promql/parser"
"github.com/grafana/loki/pkg/logql/syntax"
"github.com/grafana/loki/pkg/logqlmodel"
logql_stats "github.com/grafana/loki/pkg/logqlmodel/stats"
"github.com/grafana/loki/pkg/usagestats"
"github.com/grafana/loki/pkg/util/httpreq"
util_log "github.com/grafana/loki/pkg/util/log"
)
const (
QueryTypeMetric = "metric"
QueryTypeFilter = "filter"
QueryTypeLimited = "limited"
QueryTypeLabels = "labels"
QueryTypeSeries = "series"
latencyTypeSlow = "slow"
latencyTypeFast = "fast"
slowQueryThresholdSecond = float64(10)
)
var (
bytesPerSecond = promauto.NewHistogramVec(prometheus.HistogramOpts{
Namespace: "loki",
Name: "logql_querystats_bytes_processed_per_seconds",
Help: "Distribution of bytes processed per second for LogQL queries.",
// 50MB 100MB 200MB 400MB 600MB 800MB 1GB 2GB 3GB 4GB 5GB 6GB 7GB 8GB 9GB 10GB 15GB 20GB 30GB, 40GB 50GB 60GB
Buckets: []float64{50 * 1e6, 100 * 1e6, 400 * 1e6, 600 * 1e6, 800 * 1e6, 1 * 1e9, 2 * 1e9, 3 * 1e9, 4 * 1e9, 5 * 1e9, 6 * 1e9, 7 * 1e9, 8 * 1e9, 9 * 1e9, 10 * 1e9, 15 * 1e9, 20 * 1e9, 30 * 1e9, 40 * 1e9, 50 * 1e9, 60 * 1e9},
}, []string{"status_code", "type", "range", "latency_type"})
execLatency = promauto.NewHistogramVec(prometheus.HistogramOpts{
Namespace: "loki",
Name: "logql_querystats_latency_seconds",
Help: "Distribution of latency for LogQL queries.",
// 0.25 0.5 1 2 4 8 16 32 64 128
Buckets: prometheus.ExponentialBuckets(0.250, 2, 10),
}, []string{"status_code", "type", "range"})
chunkDownloadLatency = promauto.NewHistogramVec(prometheus.HistogramOpts{
Namespace: "loki",
Name: "logql_querystats_chunk_download_latency_seconds",
Help: "Distribution of chunk downloads latency for LogQL queries.",
// 0.25 0.5 1 2 4 8 16 32 64 128
Buckets: prometheus.ExponentialBuckets(0.250, 2, 10),
}, []string{"status_code", "type", "range"})
duplicatesTotal = promauto.NewCounter(prometheus.CounterOpts{
Namespace: "loki",
Name: "logql_querystats_duplicates_total",
Help: "Total count of duplicates found while executing LogQL queries.",
})
chunkDownloadedTotal = promauto.NewCounterVec(prometheus.CounterOpts{
Namespace: "loki",
Name: "logql_querystats_downloaded_chunk_total",
Help: "Total count of chunks downloaded found while executing LogQL queries.",
}, []string{"status_code", "type", "range"})
ingesterLineTotal = promauto.NewCounter(prometheus.CounterOpts{
Namespace: "loki",
Name: "logql_querystats_ingester_sent_lines_total",
Help: "Total count of lines sent from ingesters while executing LogQL queries.",
})
bytePerSecondMetricUsage = usagestats.NewStatistics("query_metric_bytes_per_second")
bytePerSecondLogUsage = usagestats.NewStatistics("query_log_bytes_per_second")
linePerSecondMetricUsage = usagestats.NewStatistics("query_metric_lines_per_second")
linePerSecondLogUsage = usagestats.NewStatistics("query_log_lines_per_second")
)
func RecordRangeAndInstantQueryMetrics(
ctx context.Context,
log log.Logger,
p Params,
status string,
stats logql_stats.Result,
result promql_parser.Value,
) {
var (
logger = util_log.WithContext(ctx, log)
rt = string(GetRangeType(p))
latencyType = latencyTypeFast
returnedLines = 0
)
queryType, err := QueryType(p.Query())
if err != nil {
level.Warn(logger).Log("msg", "error parsing query type", "err", err)
}
// Tag throughput metric by latency type based on a threshold.
// Latency below the threshold is fast, above is slow.
if stats.Summary.ExecTime > slowQueryThresholdSecond {
latencyType = latencyTypeSlow
}
if result != nil && result.Type() == logqlmodel.ValueTypeStreams {
returnedLines = int(result.(logqlmodel.Streams).Lines())
}
queryTags, _ := ctx.Value(httpreq.QueryTagsHTTPHeader).(string) // it's ok to be empty.
logValues := make([]interface{}, 0, 20)
logValues = append(logValues, []interface{}{
"latency", latencyType, // this can be used to filter log lines.
"query", p.Query(),
"query_type", queryType,
"range_type", rt,
"length", p.End().Sub(p.Start()),
"start_delta", time.Since(p.Start()),
"end_delta", time.Since(p.End()),
"step", p.Step(),
"duration", logql_stats.ConvertSecondsToNanoseconds(stats.Summary.ExecTime),
"status", status,
"limit", p.Limit(),
"returned_lines", returnedLines,
"throughput", strings.Replace(humanize.Bytes(uint64(stats.Summary.BytesProcessedPerSecond)), " ", "", 1),
"total_bytes", strings.Replace(humanize.Bytes(uint64(stats.Summary.TotalBytesProcessed)), " ", "", 1),
"total_entries", stats.Summary.TotalEntriesReturned,
"queue_time", logql_stats.ConvertSecondsToNanoseconds(stats.Summary.QueueTime),
"subqueries", stats.Summary.Subqueries,
"cache_chunk_req", stats.Caches.Chunk.EntriesRequested,
"cache_chunk_hit", stats.Caches.Chunk.EntriesFound,
"cache_chunk_bytes_stored", stats.Caches.Chunk.BytesSent,
"cache_chunk_bytes_fetched", stats.Caches.Chunk.BytesReceived,
"cache_index_req", stats.Caches.Index.EntriesRequested,
"cache_index_hit", stats.Caches.Index.EntriesFound,
"cache_result_req", stats.Caches.Result.EntriesRequested,
"cache_result_hit", stats.Caches.Result.EntriesFound,
}...)
logValues = append(logValues, tagsToKeyValues(queryTags)...)
level.Info(logger).Log(
logValues...,
)
bytesPerSecond.WithLabelValues(status, queryType, rt, latencyType).
Observe(float64(stats.Summary.BytesProcessedPerSecond))
execLatency.WithLabelValues(status, queryType, rt).
Observe(stats.Summary.ExecTime)
chunkDownloadLatency.WithLabelValues(status, queryType, rt).
Observe(stats.ChunksDownloadTime().Seconds())
duplicatesTotal.Add(float64(stats.TotalDuplicates()))
chunkDownloadedTotal.WithLabelValues(status, queryType, rt).
Add(float64(stats.TotalChunksDownloaded()))
ingesterLineTotal.Add(float64(stats.Ingester.TotalLinesSent))
recordUsageStats(queryType, stats)
}
func RecordLabelQueryMetrics(
ctx context.Context,
log log.Logger,
start, end time.Time,
label, status string,
stats logql_stats.Result,
) {
var (
logger = util_log.WithContext(ctx, log)
latencyType = latencyTypeFast
queryType = QueryTypeLabels
)
// Tag throughput metric by latency type based on a threshold.
// Latency below the threshold is fast, above is slow.
if stats.Summary.ExecTime > slowQueryThresholdSecond {
latencyType = latencyTypeSlow
}
level.Info(logger).Log(
"latency", latencyType,
"query_type", queryType,
"length", end.Sub(start),
"duration", time.Duration(int64(stats.Summary.ExecTime*float64(time.Second))),
"status", status,
"label", label,
"throughput", strings.Replace(humanize.Bytes(uint64(stats.Summary.BytesProcessedPerSecond)), " ", "", 1),
"total_bytes", strings.Replace(humanize.Bytes(uint64(stats.Summary.TotalBytesProcessed)), " ", "", 1),
"total_entries", stats.Summary.TotalEntriesReturned,
)
bytesPerSecond.WithLabelValues(status, queryType, "", latencyType).
Observe(float64(stats.Summary.BytesProcessedPerSecond))
execLatency.WithLabelValues(status, queryType, "").
Observe(stats.Summary.ExecTime)
chunkDownloadLatency.WithLabelValues(status, queryType, "").
Observe(stats.ChunksDownloadTime().Seconds())
duplicatesTotal.Add(float64(stats.TotalDuplicates()))
chunkDownloadedTotal.WithLabelValues(status, queryType, "").
Add(float64(stats.TotalChunksDownloaded()))
ingesterLineTotal.Add(float64(stats.Ingester.TotalLinesSent))
}
func RecordSeriesQueryMetrics(
ctx context.Context,
log log.Logger,
start, end time.Time,
match []string,
status string,
stats logql_stats.Result,
) {
var (
logger = util_log.WithContext(ctx, log)
latencyType = latencyTypeFast
queryType = QueryTypeSeries
)
// Tag throughput metric by latency type based on a threshold.
// Latency below the threshold is fast, above is slow.
if stats.Summary.ExecTime > slowQueryThresholdSecond {
latencyType = latencyTypeSlow
}
// we also log queries, useful for troubleshooting slow queries.
level.Info(logger).Log(
"latency", latencyType,
"query_type", queryType,
"length", end.Sub(start),
"duration", time.Duration(int64(stats.Summary.ExecTime*float64(time.Second))),
"status", status,
"match", strings.Join(match, ":"), // not using comma (,) as separator as matcher may already have comma (e.g: `{a="b", c="d"}`)
"throughput", strings.Replace(humanize.Bytes(uint64(stats.Summary.BytesProcessedPerSecond)), " ", "", 1),
"total_bytes", strings.Replace(humanize.Bytes(uint64(stats.Summary.TotalBytesProcessed)), " ", "", 1),
"total_entries", stats.Summary.TotalEntriesReturned,
)
bytesPerSecond.WithLabelValues(status, queryType, "", latencyType).
Observe(float64(stats.Summary.BytesProcessedPerSecond))
execLatency.WithLabelValues(status, queryType, "").
Observe(stats.Summary.ExecTime)
chunkDownloadLatency.WithLabelValues(status, queryType, "").
Observe(stats.ChunksDownloadTime().Seconds())
duplicatesTotal.Add(float64(stats.TotalDuplicates()))
chunkDownloadedTotal.WithLabelValues(status, queryType, "").
Add(float64(stats.TotalChunksDownloaded()))
ingesterLineTotal.Add(float64(stats.Ingester.TotalLinesSent))
}
func recordUsageStats(queryType string, stats logql_stats.Result) {
if queryType == QueryTypeMetric {
bytePerSecondMetricUsage.Record(float64(stats.Summary.BytesProcessedPerSecond))
linePerSecondMetricUsage.Record(float64(stats.Summary.LinesProcessedPerSecond))
} else {
bytePerSecondLogUsage.Record(float64(stats.Summary.BytesProcessedPerSecond))
linePerSecondLogUsage.Record(float64(stats.Summary.LinesProcessedPerSecond))
}
}
func QueryType(query string) (string, error) {
expr, err := syntax.ParseExpr(query)
if err != nil {
return "", err
}
switch e := expr.(type) {
case syntax.SampleExpr:
return QueryTypeMetric, nil
case syntax.LogSelectorExpr:
if e.HasFilter() {
return QueryTypeFilter, nil
}
return QueryTypeLimited, nil
default:
return "", nil
}
}
// tagsToKeyValues converts QueryTags to form that is easy to log.
// e.g: `Source=foo,Feature=beta` -> []interface{}{"source", "foo", "feature", "beta"}
// so that we could log nicely!
// If queryTags is not in canonical form then its completely ignored (e.g: `key1=value1,key2=value`)
func tagsToKeyValues(queryTags string) []interface{} {
toks := strings.FieldsFunc(queryTags, func(r rune) bool {
return r == ','
})
vals := make([]string, 0)
for _, tok := range toks {
val := strings.FieldsFunc(tok, func(r rune) bool {
return r == '='
})
if len(val) != 2 {
continue
}
vals = append(vals, val...)
}
res := make([]interface{}, 0, len(vals))
for _, val := range vals {
res = append(res, strings.ToLower(val))
}
return res
}