Metrics Module
Overview
Yokai provides a fxmetrics module, allowing your application to provide metrics.
It wraps the Prometheus module.
Installation
The fxmetrics module is automatically loaded by Yokai's core.
When you use a Yokai application template
, you have nothing to install, it's ready to use.
Configuration
modules:
metrics:
collect:
build: true # to collect build infos metrics (disabled by default)
go: true # to collect go metrics (disabled by default)
process: true # to collect process metrics (disabled by default)
Usage
This module will enable Yokai to collect registered metrics collectors, and make them available to a metrics registry in its dependency injection system.
Metrics creation
You can add metrics anywhere in your application.
For example:
package service
import (
"fmt"
"github.com/prometheus/client_golang/prometheus"
)
var ExampleCounter = prometheus.NewCounter(prometheus.CounterOpts{
Name: "example_total",
Help: "Example counter",
})
type ExampleService struct {}
func NewExampleService() *ExampleService {
return &ExampleService{}
}
func (s *ExampleService) DoSomething() {
// service logic
fmt.Println("do something")
// increment counter
ExampleCounter.Inc()
}
Metrics registration
Even if convenient, it's recommended to NOT use the promauto way of registering metrics, as it uses a global registry that leads to data race conditions (especially while testing).
You can instead register your metrics collector with the AsMetricsCollector()
function:
package internal
import (
"github.com/ankorstore/yokai/fxmetrics"
"github.com/foo/bar/internal/service"
"go.uber.org/fx"
)
func Register() fx.Option {
return fx.Options(
// register the ExampleCounter metrics collector
fxmetrics.AsMetricsCollector(service.ExampleCounter),
// ...
)
}
You can also register several metrics collectors at once with AsMetricsCollectors()
.
Metrics execution
Yokai's core HTTP server will automatically:
- expose the configured metrics endpoints
- use the registry to expose the registered metrics collectors
Following previous example, after invoking the ExampleService
, the metrics endpoint will return:
# ...
# HELP example_total Example counter
# TYPE example_total counter
example_total 1
You can also get, real time, the status of your metrics on the core dashboard: