diff --git a/counter_example_test.go b/counter_example_test.go new file mode 100644 index 0000000..c485df6 --- /dev/null +++ b/counter_example_test.go @@ -0,0 +1,41 @@ +package metrics_test + +import ( + "fmt" + "github.com/VictoriaMetrics/metrics" +) + +func ExampleCounter() { + // Define a counter in global scope. + var c = metrics.NewCounter(`metric_total{label1="value1", label2="value2"}`) + + // Increment the counter when needed. + for i := 0; i < 10; i++ { + c.Inc() + } + n := c.Get() + fmt.Println(n) + + // Output: + // 10 +} + +func ExampleCounter_vec() { + for i := 0; i < 3; i++ { + // Dynamically construct metric name and pass it to GetOrCreateCounter. + name := fmt.Sprintf(`metric_total{label1=%q, label2="%d"}`, "value1", i) + metrics.GetOrCreateCounter(name).Add(i + 1) + } + + // Read counter values. + for i := 0; i < 3; i++ { + name := fmt.Sprintf(`metric_total{label1=%q, label2="%d"}`, "value1", i) + n := metrics.GetOrCreateCounter(name).Get() + fmt.Println(n) + } + + // Output: + // 1 + // 2 + // 3 +} diff --git a/gauge_example_test.go b/gauge_example_test.go new file mode 100644 index 0000000..56a6e47 --- /dev/null +++ b/gauge_example_test.go @@ -0,0 +1,18 @@ +package metrics_test + +import ( + "fmt" + "runtime" + + "github.com/VictoriaMetrics/metrics" +) + +func ExampleGauge() { + // Define a gauge exporting the number of goroutines. + var g = metrics.NewGauge(`goroutines_count`, func() float64 { + return float64(runtime.NumGoroutine()) + }) + + // Obtain gauge value. + fmt.Println(g.Get()) +} diff --git a/metrics_example_test.go b/metrics_example_test.go new file mode 100644 index 0000000..0ac08ae --- /dev/null +++ b/metrics_example_test.go @@ -0,0 +1,14 @@ +package metrics_test + +import ( + "net/http" + + "github.com/VictoriaMetrics/metrics" +) + +func ExampleWritePrometheus() { + // Export all the registered metrics in Prometheus format at `/metrics` http path. + http.HandleFunc("/metrics", func(w http.ResponseWriter, req *http.Request) { + metrics.WritePrometheus(w, true) + }) +} diff --git a/summary_example_test.go b/summary_example_test.go new file mode 100644 index 0000000..09dc57f --- /dev/null +++ b/summary_example_test.go @@ -0,0 +1,31 @@ +package metrics_test + +import ( + "fmt" + "time" + + "github.com/VictoriaMetrics/metrics" +) + +func ExampleSummary() { + // Define a summary in global scope. + var s = metrics.NewSummary(`request_duration_seconds{path="/foo/bar"}`) + + // Update the summary with the duration of processRequest call. + startTime := time.Now() + processRequest() + s.UpdateDuration(startTime) +} + +func ExampleSummary_vec() { + for i := 0; i < 3; i++ { + // Dynamically construct metric name and pass it to GetOrCreateSummary. + name := fmt.Sprintf(`response_size_bytes{path=%q}`, "/foo/bar") + response := processRequest() + metrics.GetOrCreateSummary(name).Update(float64(len(response))) + } +} + +func processRequest() string { + return "foobar" +}