rio/internal/pages/metrics.go

75 lines
1.5 KiB
Go
Raw Normal View History

2024-02-02 20:07:29 +00:00
package pages
import (
"encoding/json"
"io/ioutil"
2024-02-02 20:07:29 +00:00
"net/http"
"strconv"
"strings"
"time"
log "github.com/sirupsen/logrus"
)
type LokiMetricConfig struct {
Url string
Enabled bool
}
// Checks if we should send a metric ping to Loki based on the served path.
func (c *LokiMetricConfig) shouldSendMetrics(path string) bool {
return strings.HasSuffix(path, ".html") && c.Enabled
}
func (c *LokiMetricConfig) sendMetricPing(domain, path string) {
data := map[string]interface{}{
2024-02-02 20:36:58 +00:00
"streams": []map[string]interface{}{
2024-02-02 20:07:29 +00:00
{
"stream": map[string]string{
// Labels
"service": "rio",
"domain": domain,
"type": "metric",
},
"values": [][]interface{}{
{
strconv.Itoa(int(time.Now().UnixNano())),
"path=" + path,
},
},
},
},
}
jsonData, err := json.Marshal(data)
if err != nil {
log.Errorf("Failed to send metric ping to Loki: %v", err)
return
}
log.Debugf("Sending payload %s", string(jsonData))
2024-02-02 20:07:29 +00:00
// Send the ping to the Loki server
go func() {
res, err := http.Post(
2024-02-02 20:07:29 +00:00
c.Url,
"application/json",
strings.NewReader(string(jsonData)),
)
if err != nil {
log.Errorf("Failed to send payload to Loki: %v", err)
return
}
defer res.Body.Close()
if res.StatusCode != 204 {
log.Errorf("Loki returned non-204 status code %d", res.StatusCode)
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Warnf("Failed to read body. No more specific error message")
return
}
log.Errorf("-> %s", body)
}
2024-02-02 20:07:29 +00:00
}()
}