Added examples

This commit is contained in:
Aliaksandr Valialkin 2019-04-11 17:26:20 +03:00
parent 4ea76dd6b8
commit bded4324a5
4 changed files with 104 additions and 0 deletions

41
counter_example_test.go Normal file
View File

@ -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
}

18
gauge_example_test.go Normal file
View File

@ -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())
}

14
metrics_example_test.go Normal file
View File

@ -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)
})
}

31
summary_example_test.go Normal file
View File

@ -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"
}