aboutsummaryrefslogtreecommitdiffstats
path: root/metrics/prometheus/prometheus.go
blob: 9ad5ec7e9929d61480c2cc67748a9b727a6560d2 (plain) (blame)
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
// Copyright 2019 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

// Package prometheus exposes go-metrics into a Prometheus format.
package prometheus

import (
    "fmt"
    "net/http"
    "sort"

    "github.com/ethereum/go-ethereum/log"
    "github.com/ethereum/go-ethereum/metrics"
)

// Handler returns an HTTP handler which dump metrics in Prometheus format.
func Handler(reg metrics.Registry) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Gather and pre-sort the metrics to avoid random listings
        var names []string
        reg.Each(func(name string, i interface{}) {
            names = append(names, name)
        })
        sort.Strings(names)

        // Aggregate all the metris into a Prometheus collector
        c := newCollector()

        for _, name := range names {
            i := reg.Get(name)

            switch m := i.(type) {
            case metrics.Counter:
                c.addCounter(name, m.Snapshot())
            case metrics.Gauge:
                c.addGauge(name, m.Snapshot())
            case metrics.GaugeFloat64:
                c.addGaugeFloat64(name, m.Snapshot())
            case metrics.Histogram:
                c.addHistogram(name, m.Snapshot())
            case metrics.Meter:
                c.addMeter(name, m.Snapshot())
            case metrics.Timer:
                c.addTimer(name, m.Snapshot())
            case metrics.ResettingTimer:
                c.addResettingTimer(name, m.Snapshot())
            default:
                log.Warn("Unknown Prometheus metric type", "type", fmt.Sprintf("%T", i))
            }
        }
        w.Header().Add("Content-Type", "text/plain")
        w.Header().Add("Content-Length", fmt.Sprint(c.buff.Len()))
        w.Write(c.buff.Bytes())
    })
}