metrics: avoid sprintf

This commit is contained in:
aler9 2021-01-15 18:50:31 +01:00
parent 3b04ba36c3
commit 9b052f1cdc
1 changed files with 21 additions and 16 deletions

View File

@ -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)