Skip to content

Commit

Permalink
allow passing metric names with labels into Write{Counter,Gauge}{Uint…
Browse files Browse the repository at this point in the history
…64,Float64} functions
  • Loading branch information
valyala committed Dec 19, 2023
1 parent 9dc7358 commit 2d7f9a1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 18 deletions.
25 changes: 17 additions & 8 deletions metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,6 @@ type namedMetric struct {
isAux bool
}

func (nm *namedMetric) family() string {
n := strings.IndexByte(nm.name, '{')
if n < 0 {
return nm.name
}
return nm.name[:n]
}

type metric interface {
marshalTo(prefix string, w io.Writer)
metricType() string
Expand Down Expand Up @@ -306,3 +298,20 @@ func writeMetricFloat64(w io.Writer, metricName, metricType string, value float6
writeMetadataIfNeeded(w, metricName, metricType)
fmt.Fprintf(w, "%s %g\n", metricName, value)
}

func writeMetadataIfNeeded(w io.Writer, metricName, metricType string) {
if !isMetadataEnabled() {
return
}
metricFamily := getMetricFamily(metricName)
fmt.Fprintf(w, "# HELP %s\n", metricFamily)
fmt.Fprintf(w, "# TYPE %s %s\n", metricFamily, metricType)
}

func getMetricFamily(metricName string) string {
n := strings.IndexByte(metricName, '{')
if n < 0 {
return metricName
}
return metricName[:n]
}
12 changes: 2 additions & 10 deletions set.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ func (s *Set) WritePrometheus(w io.Writer) {

prevMetricFamily := ""
for _, nm := range sa {
metricFamily := nm.family()
metricFamily := getMetricFamily(nm.name)
if metricFamily != prevMetricFamily {
// write meta info only once per metric family
metricType := nm.metric.metricType()
writeMetadataIfNeeded(&bb, metricFamily, metricType)
writeMetadataIfNeeded(&bb, nm.name, metricType)
prevMetricFamily = metricFamily
}
// Call marshalTo without the global lock, since certain metric types such as Gauge
Expand All @@ -63,14 +63,6 @@ func (s *Set) WritePrometheus(w io.Writer) {
w.Write(bb.Bytes())
}

func writeMetadataIfNeeded(w io.Writer, metricFamily, metricType string) {
if !isMetadataEnabled() {
return
}
fmt.Fprintf(w, "# HELP %s\n", metricFamily)
fmt.Fprintf(w, "# TYPE %s %s\n", metricFamily, metricType)
}

// NewHistogram creates and returns new histogram in s with the given name.
//
// name must be valid Prometheus-compatible metric with possible labels.
Expand Down

0 comments on commit 2d7f9a1

Please sign in to comment.