github.com/defi-hunter/go-ethereum@v1.9.7-0.20191031044858-21506be82b68/metrics/prometheus/prometheus.go (about)

     1  // Copyright 2019 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Package prometheus exposes go-metrics into a Prometheus format.
    18  package prometheus
    19  
    20  import (
    21  	"fmt"
    22  	"net/http"
    23  	"sort"
    24  
    25  	"github.com/Fantom-foundation/go-ethereum/log"
    26  	"github.com/Fantom-foundation/go-ethereum/metrics"
    27  )
    28  
    29  // Handler returns an HTTP handler which dump metrics in Prometheus format.
    30  func Handler(reg metrics.Registry) http.Handler {
    31  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    32  		// Gather and pre-sort the metrics to avoid random listings
    33  		var names []string
    34  		reg.Each(func(name string, i interface{}) {
    35  			names = append(names, name)
    36  		})
    37  		sort.Strings(names)
    38  
    39  		// Aggregate all the metris into a Prometheus collector
    40  		c := newCollector()
    41  
    42  		for _, name := range names {
    43  			i := reg.Get(name)
    44  
    45  			switch m := i.(type) {
    46  			case metrics.Counter:
    47  				c.addCounter(name, m.Snapshot())
    48  			case metrics.Gauge:
    49  				c.addGauge(name, m.Snapshot())
    50  			case metrics.GaugeFloat64:
    51  				c.addGaugeFloat64(name, m.Snapshot())
    52  			case metrics.Histogram:
    53  				c.addHistogram(name, m.Snapshot())
    54  			case metrics.Meter:
    55  				c.addMeter(name, m.Snapshot())
    56  			case metrics.Timer:
    57  				c.addTimer(name, m.Snapshot())
    58  			case metrics.ResettingTimer:
    59  				c.addResettingTimer(name, m.Snapshot())
    60  			default:
    61  				log.Warn("Unknown Prometheus metric type", "type", fmt.Sprintf("%T", i))
    62  			}
    63  		}
    64  		w.Header().Add("Content-Type", "text/plain")
    65  		w.Header().Add("Content-Length", fmt.Sprint(c.buff.Len()))
    66  		w.Write(c.buff.Bytes())
    67  	})
    68  }