chore(exporter): rework exporter to fix wrong histogram usage and cache metric data
This commit is contained in:
parent
4d2a7acebc
commit
8b7f45563a
6 changed files with 180 additions and 312 deletions
|
@ -2,67 +2,19 @@ package exporter
|
|||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
)
|
||||
|
||||
type RequestData struct {
|
||||
Latency time.Duration
|
||||
Request *http.Request
|
||||
Start time.Time
|
||||
}
|
||||
|
||||
type RequestDataQueue struct {
|
||||
mu sync.Mutex
|
||||
data []RequestData
|
||||
}
|
||||
|
||||
func NewRequestDataQueue() *RequestDataQueue {
|
||||
return &RequestDataQueue{
|
||||
data: []RequestData{},
|
||||
}
|
||||
}
|
||||
|
||||
func (q *RequestDataQueue) Add(data RequestData) {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
q.data = append(q.data, data)
|
||||
}
|
||||
|
||||
func (q *RequestDataQueue) ConsumeAll() []RequestData {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
data := q.data
|
||||
q.data = nil
|
||||
return data
|
||||
}
|
||||
|
||||
type Middleware struct {
|
||||
queue *RequestDataQueue
|
||||
}
|
||||
|
||||
func NewMiddleware(queue *RequestDataQueue) func(next http.Handler) http.Handler {
|
||||
m := Middleware{
|
||||
queue: queue,
|
||||
}
|
||||
return m.handler
|
||||
metrics *Metrics
|
||||
}
|
||||
|
||||
func (m Middleware) handler(next http.Handler) http.Handler {
|
||||
fn := func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
next.ServeHTTP(ww, r)
|
||||
|
||||
m.queue.Add(
|
||||
RequestData{
|
||||
Latency: time.Since(start),
|
||||
Request: r,
|
||||
Start: start,
|
||||
},
|
||||
)
|
||||
}
|
||||
return http.HandlerFunc(fn)
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
timer := prometheus.NewTimer(m.metrics.metricRequestLatency)
|
||||
next.ServeHTTP(w, r)
|
||||
m.metrics.metricRequestsTotal.Inc()
|
||||
timer.ObserveDuration()
|
||||
})
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue