Skip to content

Commit

Permalink
add host into the metrics output for zipserver
Browse files Browse the repository at this point in the history
  • Loading branch information
leafo committed Nov 24, 2023
1 parent 6bb9e5d commit 1e66858
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
9 changes: 8 additions & 1 deletion zipserver/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package zipserver
import (
"fmt"
"net/http"
"os"
"reflect"
"strings"
"sync/atomic"
Expand All @@ -24,14 +25,20 @@ func (m *MetricsCounter) RenderMetrics() string {

valueOfMetrics := reflect.ValueOf(m).Elem()

hostname, ok := os.LookupEnv("ZIPSERVER_METRICS_HOST")
if !ok {
hostname, _ = os.Hostname()
}

for i := 0; i < valueOfMetrics.NumField(); i++ {
metricTag := valueOfMetrics.Type().Field(i).Tag.Get("metric")
if metricTag == "" {
continue
}
fieldValue := valueOfMetrics.Field(i).Addr().Interface().(*atomic.Int64).Load()

Check failure on line 38 in zipserver/metrics.go

View workflow job for this annotation

GitHub Actions / build

undefined: atomic.Int64

metrics.WriteString(fmt.Sprintf("%s %v\n", metricTag, fieldValue))
metrics.WriteString(fmt.Sprintf("%s{host=\"%s\"} %v\n", metricTag, hostname, fieldValue))

}

return metrics.String()
Expand Down
9 changes: 5 additions & 4 deletions zipserver/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,11 @@ func Test_Metrics(t *testing.T) {
assert.Equal(t, int64(1), metrics.TotalExtractedFiles.Load())

// Test RenderMetrics
expectedMetrics := `zipserver_requests_total 1
zipserver_errors_total 0
zipserver_extracted_files_total 1
zipserver_copied_files_total 0
t.Setenv("ZIPSERVER_METRICS_HOST", "localhost")
expectedMetrics := `zipserver_requests_total{host="localhost"} 1
zipserver_errors_total{host="localhost"} 0
zipserver_extracted_files_total{host="localhost"} 1
zipserver_copied_files_total{host="localhost"} 0
`

assert.Equal(t, expectedMetrics, metrics.RenderMetrics())
Expand Down

0 comments on commit 1e66858

Please sign in to comment.