MCPcopy
hub / github.com/prometheus/client_golang / ExampleCollectorFunc

Function ExampleCollectorFunc

prometheus/examples_test.go:743–788  ·  prometheus/examples_test.go::ExampleCollectorFunc

Using CollectorFunc that registers the metric info for the HTTP requests.

()

Source from the content-addressed store, hash-verified

741
742// Using CollectorFunc that registers the metric info for the HTTP requests.
743func ExampleCollectorFunc() {
744 desc := prometheus.NewDesc(
745 "http_requests_info",
746 "Information about the received HTTP requests.",
747 []string{"code", "method"},
748 nil,
749 )
750
751 // Example 1: 42 GET requests with 200 OK status code.
752 collector := prometheus.CollectorFunc(func(ch chan<- prometheus.Metric) {
753 ch <- prometheus.MustNewConstMetric(
754 desc,
755 prometheus.CounterValue, // Metric type: Counter
756 42, // Value
757 "200", // Label value: HTTP status code
758 "GET", // Label value: HTTP method
759 )
760
761 // Example 2: 15 POST requests with 404 Not Found status code.
762 ch <- prometheus.MustNewConstMetric(
763 desc,
764 prometheus.CounterValue,
765 15,
766 "404",
767 "POST",
768 )
769 })
770
771 prometheus.MustRegister(collector)
772
773 // Just for demonstration, let's check the state of the metric by registering
774 // it with a custom registry and then let it collect the metrics.
775
776 reg := prometheus.NewRegistry()
777 reg.MustRegister(collector)
778
779 metricFamilies, err := reg.Gather()
780 if err != nil || len(metricFamilies) != 1 {
781 panic("unexpected behavior of custom test registry")
782 }
783
784 fmt.Println(toNormalizedJSON(sanitizeMetricFamily(metricFamilies[0])))
785
786 // Output:
787 // {"name":"http_requests_info","help":"Information about the received HTTP requests.","type":"COUNTER","metric":[{"label":[{"name":"code","value":"200"},{"name":"method","value":"GET"}],"counter":{"value":42}},{"label":[{"name":"code","value":"404"},{"name":"method","value":"POST"}],"counter":{"value":15}}]}
788}
789
790// Using WrapCollectorWith to un-register metrics registered by a third party lib.
791// newThirdPartyLibFoo illustrates a constructor from a third-party lib that does

Callers

nothing calls this directly

Calls 10

MustRegisterMethod · 0.95
GatherMethod · 0.95
NewDescFunction · 0.92
CollectorFuncFuncType · 0.92
MustNewConstMetricFunction · 0.92
MustRegisterFunction · 0.92
NewRegistryFunction · 0.92
toNormalizedJSONFunction · 0.85
sanitizeMetricFamilyFunction · 0.85
PrintlnMethod · 0.65

Tested by

no test coverage detected