From 9b052f1cdc1467f1a72993b2be633bc7e84226e8 Mon Sep 17 00:00:00 2001 From: aler9 <46489434+aler9@users.noreply.github.com> Date: Fri, 15 Jan 2021 18:50:31 +0100 Subject: [PATCH] metrics: avoid sprintf --- internal/metrics/metrics.go | 37 +++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/internal/metrics/metrics.go b/internal/metrics/metrics.go index fd0086e3..e5186482 100644 --- a/internal/metrics/metrics.go +++ b/internal/metrics/metrics.go @@ -2,10 +2,10 @@ package metrics import ( "context" - "fmt" "io" "net" "net/http" + "strconv" "sync/atomic" "time" @@ -17,6 +17,11 @@ const ( address = ":9998" ) +func formatMetric(key string, value int64, nowUnix int64) string { + return key + " " + strconv.FormatInt(value, 10) + " " + + strconv.FormatInt(nowUnix, 10) + "\n" +} + // Parent is implemented by program. type Parent interface { Log(logger.Level, string, ...interface{}) @@ -69,7 +74,7 @@ func (m *Metrics) run() { } func (m *Metrics) onMetrics(w http.ResponseWriter, req *http.Request) { - now := time.Now().UnixNano() / 1000000 + nowUnix := time.Now().UnixNano() / 1000000 countClients := atomic.LoadInt64(m.stats.CountClients) countPublishers := atomic.LoadInt64(m.stats.CountPublishers) @@ -80,20 +85,20 @@ func (m *Metrics) onMetrics(w http.ResponseWriter, req *http.Request) { countSourcesRtmpRunning := atomic.LoadInt64(m.stats.CountSourcesRtmpRunning) out := "" - out += fmt.Sprintf("rtsp_clients{state=\"idle\"} %d %v\n", - countClients-countPublishers-countReaders, now) - out += fmt.Sprintf("rtsp_clients{state=\"publishing\"} %d %v\n", - countPublishers, now) - out += fmt.Sprintf("rtsp_clients{state=\"reading\"} %d %v\n", - countReaders, now) - out += fmt.Sprintf("rtsp_sources{type=\"rtsp\",state=\"idle\"} %d %v\n", - countSourcesRtsp-countSourcesRtspRunning, now) - out += fmt.Sprintf("rtsp_sources{type=\"rtsp\",state=\"running\"} %d %v\n", - countSourcesRtspRunning, now) - out += fmt.Sprintf("rtsp_sources{type=\"rtmp\",state=\"idle\"} %d %v\n", - countSourcesRtmp-countSourcesRtmpRunning, now) - out += fmt.Sprintf("rtsp_sources{type=\"rtmp\",state=\"running\"} %d %v\n", - countSourcesRtmpRunning, now) + out += formatMetric("rtsp_clients{state=\"idle\"}", + countClients-countPublishers-countReaders, nowUnix) + out += formatMetric("rtsp_clients{state=\"publishing\"}", + countPublishers, nowUnix) + out += formatMetric("rtsp_clients{state=\"reading\"}", + countReaders, nowUnix) + out += formatMetric("rtsp_sources{type=\"rtsp\",state=\"idle\"}", + countSourcesRtsp-countSourcesRtspRunning, nowUnix) + out += formatMetric("rtsp_sources{type=\"rtsp\",state=\"running\"}", + countSourcesRtspRunning, nowUnix) + out += formatMetric("rtsp_sources{type=\"rtmp\",state=\"idle\"}", + countSourcesRtmp-countSourcesRtmpRunning, nowUnix) + out += formatMetric("rtsp_sources{type=\"rtmp\",state=\"running\"}", + countSourcesRtmpRunning, nowUnix) w.WriteHeader(http.StatusOK) io.WriteString(w, out)