/
prometheus.go
85 lines (72 loc) · 1.8 KB
/
prometheus.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
// Copyright 2015 Google Inc. All Rights Reserved.
// This file is available under the Apache license.
package exporter
import (
"expvar"
"fmt"
"net/http"
"sort"
"strings"
"github.com/google/mtail/metrics"
)
var (
metricExportTotal = expvar.NewInt("metric_export_total")
)
const (
prometheusFormat = "%s{%s} %s\n"
)
func noHyphens(s string) string {
return strings.Replace(s, "-", "_", -1)
}
// HandlePrometheusMetrics exports the metrics in a format readable by
// Prometheus via HTTP.
func (e *Exporter) HandlePrometheusMetrics(w http.ResponseWriter, r *http.Request) {
e.store.RLock()
defer e.store.RUnlock()
w.Header().Add("Content-type", "text/plain; version=0.0.4")
for _, ml := range e.store.Metrics {
emittype := true
for _, m := range ml {
m.RLock()
metricExportTotal.Add(1)
if emittype {
fmt.Fprintf(w,
"# TYPE %s %s\n",
noHyphens(m.Name),
kindToPrometheusType(m.Kind))
emittype = false
}
lc := make(chan *metrics.LabelSet)
go m.EmitLabelSets(lc)
for l := range lc {
if m.Source != "" {
fmt.Fprintf(w, "# %s defined at %s\n", noHyphens(m.Name), m.Source)
}
line := metricToPrometheus(e.o, m, l)
fmt.Fprint(w, line)
}
m.RUnlock()
}
}
}
func metricToPrometheus(options Options, m *metrics.Metric, l *metrics.LabelSet) string {
var s []string
for k, v := range l.Labels {
// Prometheus quotes the value of each label=value pair.
s = append(s, fmt.Sprintf("%s=%q", k, v))
}
sort.Strings(s)
if !options.OmitProgLabel {
s = append(s, fmt.Sprintf("prog=\"%s\"", m.Program))
}
return fmt.Sprintf(prometheusFormat,
noHyphens(m.Name),
strings.Join(s, ","),
l.Datum.ValueString())
}
func kindToPrometheusType(kind metrics.Kind) string {
if kind != metrics.Timer {
return strings.ToLower(kind.String())
}
return "gauge"
}