基本介绍

监控指标的代码开发直接使用框架主库的 gmetric 组件即可,但由于 gmetric 组件实际上只是定义了监控指标的相关接口,并且默认提供的 NoopPerformer,默认监控指标特性是关闭的。因此需要引入具体的接口实现组件才能真正开启监控指标特性。框架社区提供了社区组件 github.com/gogf/gf/contrib/metric/otelmetric/v2,使用了 OpenTelemetry 实现框架的监控指标接口,引入该社区组件并且执行监控指标管理对象创建即可开启监控指标特性。 otelmetric 组件源码地址: https://github.com/gogf/gf/tree/master/contrib/metric/otelmetric

我们通过一个简单的监控指标实现示例来介绍一下监控指标组件的基本使用。

  1. package main
  2. import (
  3. "go.opentelemetry.io/otel/sdk/metric"
  4. "go.opentelemetry.io/otel/sdk/metric/metricdata"
  5. "github.com/gogf/gf/contrib/metric/otelmetric/v2"
  6. "github.com/gogf/gf/v2/frame/g"
  7. "github.com/gogf/gf/v2/os/gctx"
  8. "github.com/gogf/gf/v2/os/gmetric"
  9. )
  10. var (
  11. meter = gmetric.GetGlobalProvider().Meter(gmetric.MeterOption{
  12. Instrument: "github.com/gogf/gf/example/metric/basic",
  13. InstrumentVersion: "v1.0",
  14. })
  15. counter = meter.MustCounter(
  16. "goframe.metric.demo.counter",
  17. gmetric.MetricOption{
  18. Help: "This is a simple demo for Counter usage",
  19. Unit: "bytes",
  20. },
  21. )
  22. )
  23. func main() {
  24. var (
  25. ctx = gctx.New()
  26. reader = metric.NewManualReader()
  27. )
  28. provider := otelmetric.MustProvider(otelmetric.WithReader(reader))
  29. provider.SetAsGlobal()
  30. defer provider.Shutdown(ctx)
  31. counter.Inc(ctx)
  32. counter.Add(ctx, 10)
  33. var (
  34. rm = metricdata.ResourceMetrics{}
  35. err = reader.Collect(ctx, &rm)
  36. )
  37. if err != nil {
  38. g.Log().Fatal(ctx, err)
  39. }
  40. g.DumpJson(rm)
  41. }

指标管理组件的创建

通过 gmetric.GetGlobalProvider() 方法可以获取全局的监控 指标管理对象该对象是一个单例设计,全局只能有一个。并通过该对象的 Meter 方法可以创建/获取对应的 组件对象。组件对象用于管理该组件下所有的监控指标。在创建组件对象时通常需要定义组件( Instrument)的名称以及版本(虽然也可以为空,但为了方便后续维护建议都设置上)。

  1. meter = gmetric.GetGlobalProvider().Meter(gmetric.MeterOption{
  2. Instrument: "github.com/gogf/gf/example/metric/basic",
  3. InstrumentVersion: "v1.0",
  4. })

其中的 gmeter.MeterOption 数据结构如下:

  1. // MeterOption holds the creation option for a Meter.
  2. type MeterOption struct {
  3. // Instrument is the instrumentation name to bind this Metric to a global MeterProvider.
  4. // This is an optional configuration for a metric.
  5. Instrument string
  6. // InstrumentVersion is the instrumentation version to bind this Metric to a global MeterProvider.
  7. // This is an optional configuration for a metric.
  8. InstrumentVersion string
  9. // Attributes holds the constant key-value pair description metadata for all metrics of Meter.
  10. // This is an optional configuration for a meter.
  11. Attributes Attributes
  12. }

监控指标对象的创建

通过 Meter 接口对象,我们可以在该组件下创建对应的各种指标。指标有各种数据类型,因此 Meter 接口的定义如下:

  1. // Meter hold the functions for kinds of Metric creating.
  2. type Meter interface {
  3. // Counter creates and returns a new Counter.
  4. Counter(name string, option MetricOption) (Counter, error)
  5. // UpDownCounter creates and returns a new UpDownCounter.
  6. UpDownCounter(name string, option MetricOption) (UpDownCounter, error)
  7. // Histogram creates and returns a new Histogram.
  8. Histogram(name string, option MetricOption) (Histogram, error)
  9. // ObservableCounter creates and returns a new ObservableCounter.
  10. ObservableCounter(name string, option MetricOption) (ObservableCounter, error)
  11. // ObservableUpDownCounter creates and returns a new ObservableUpDownCounter.
  12. ObservableUpDownCounter(name string, option MetricOption) (ObservableUpDownCounter, error)
  13. // ObservableGauge creates and returns a new ObservableGauge.
  14. ObservableGauge(name string, option MetricOption) (ObservableGauge, error)
  15. // MustCounter creates and returns a new Counter.
  16. // It panics if any error occurs.
  17. MustCounter(name string, option MetricOption) Counter
  18. // MustUpDownCounter creates and returns a new UpDownCounter.
  19. // It panics if any error occurs.
  20. MustUpDownCounter(name string, option MetricOption) UpDownCounter
  21. // MustHistogram creates and returns a new Histogram.
  22. // It panics if any error occurs.
  23. MustHistogram(name string, option MetricOption) Histogram
  24. // MustObservableCounter creates and returns a new ObservableCounter.
  25. // It panics if any error occurs.
  26. MustObservableCounter(name string, option MetricOption) ObservableCounter
  27. // MustObservableUpDownCounter creates and returns a new ObservableUpDownCounter.
  28. // It panics if any error occurs.
  29. MustObservableUpDownCounter(name string, option MetricOption) ObservableUpDownCounter
  30. // MustObservableGauge creates and returns a new ObservableGauge.
  31. // It panics if any error occurs.
  32. MustObservableGauge(name string, option MetricOption) ObservableGauge
  33. // RegisterCallback registers callback on certain metrics.
  34. // A callback is bound to certain component and version, it is called when the associated metrics are read.
  35. // Multiple callbacks on the same component and version will be called by their registered sequence.
  36. RegisterCallback(callback Callback, canBeCallbackMetrics ...ObservableMetric) error
  37. // MustRegisterCallback performs as RegisterCallback, but it panics if any error occurs.
  38. MustRegisterCallback(callback Callback, canBeCallbackMetrics ...ObservableMetric)
  39. }

以本示例代码中使用的 meter.MustCounter 方法来介绍,该方法是创建一个 Counter 同步指标,同时由于我们偷懒这个使用了 Must* 方法,也就是说如果创建指标失败,那么这个方法会 panic 报错。在创建指标对象时,指标名称 name 是必须参数,另外的 MetricOption 是可选项参数,用于进一步描述指标信息。 MetricOption 的数据结构定义如下:

  1. // MetricOption holds the basic options for creating a metric.
  2. type MetricOption struct {
  3. // Help provides information about this Histogram.
  4. // This is an optional configuration for a metric.
  5. Help string
  6. // Unit is the unit for metric value.
  7. // This is an optional configuration for a metric.
  8. Unit string
  9. // Attributes holds the constant key-value pair description metadata for this metric.
  10. // This is an optional configuration for a metric.
  11. Attributes Attributes
  12. // Buckets defines the buckets into which observations are counted.
  13. // For Histogram metric only.
  14. // A histogram metric uses default buckets if no explicit buckets configured.
  15. Buckets []float64
  16. // Callback function for metric, which is called when metric value changes.
  17. // For observable metric only.
  18. // If an observable metric has either Callback attribute nor global callback configured, it does nothing.
  19. Callback MetricCallback
  20. }

初始化监控指标实现

通过 otelmetric.MustProvider 创建方法即可创建并初始化监控指标管理对象。

  1. provider := otelmetric.MustProvider(otelmetric.WithReader(reader))
  2. provider.SetAsGlobal()
  3. defer provider.Shutdown(ctx)

前面我们有介绍到, GlobalProvider 其实是一个单例的指标管理对象,因此这里通过 provider.SetAsGlobal 方法调用可以将该对象设置为全局的指标管理对象,便于后续的指标创建均基于该对象创建。

我们在 main 函数中通过 defer provider.ShutDown 方法调用便于在程序结束时优雅结束指标管理对象,例如对象中的指标缓存及时输出到目标端。

监控指标对象的使用

不同的指标对象有不同的操作方法用于实现指标数值的变化。以示例中的 Counter 指标类型为例,其接口定义如下:

  1. // Counter is a Metric that represents a single numerical value that can ever
  2. // goes up.
  3. type Counter interface {
  4. Metric
  5. CounterPerformer
  6. }
  7. // CounterPerformer performs operations for Counter metric.
  8. type CounterPerformer interface {
  9. // Inc increments the counter by 1. Use Add to increment it by arbitrary
  10. // non-negative values.
  11. Inc(ctx context.Context, option ...Option)
  12. // Add adds the given value to the counter. It panics if the value is < 0.
  13. Add(ctx context.Context, increment float64, option ...Option)
  14. }

可以看到, Counter 指标主要可以执行 IncAdd 两个操作方法。其中还有一个 Metric 的接口,所有的指标均实现了该接口用于获取当前指标的基础信息,其接口定义如下:

  1. // Metric models a single sample value with its metadata being exported.
  2. type Metric interface {
  3. // Info returns the basic information of a Metric.
  4. Info() MetricInfo
  5. }
  6. // MetricInfo exports information of the Metric.
  7. type MetricInfo interface {
  8. Key() string // Key returns the unique string key of the metric.
  9. Name() string // Name returns the name of the metric.
  10. Help() string // Help returns the help description of the metric.
  11. Unit() string // Unit returns the unit name of the metric.
  12. Type() MetricType // Type returns the type of the metric.
  13. Attributes() Attributes // Attributes returns the constant attribute slice of the metric.
  14. Instrument() InstrumentInfo // InstrumentInfo returns the instrument info of the metric.
  15. }
  16. // InstrumentInfo exports the instrument information of a metric.
  17. type InstrumentInfo interface {
  18. Name() string // Name returns the instrument name of the metric.
  19. Version() string // Version returns the instrument version of the metric.
  20. }

监控指标的数据读取

通过上一章节介绍的 OpenTelemetry 组件关系我们知道,如果想要使用指标必须要通过 MetricReader,因此在该示例代码中我们通过 OpenTelemetry 官方社区开源组件中最常用的 ManualReader 来简单实现指标数据读取, ManualReaderOpenTelemetry 官方社区提供的实现。

  1. reader = metric.NewManualReader()

并通过 WithReader 方法配置到 Provider 中:

  1. provider := otelmetric.MustProvider(otelmetric.WithReader(reader))

随后通过 Collect 方法可以获取当前所有的指标数据:

  1. var (
  2. rm = metricdata.ResourceMetrics{}
  3. err = reader.Collect(ctx, &rm)
  4. )
  5. if err != nil {
  6. g.Log().Fatal(ctx, err)
  7. }
  8. g.DumpJson(rm)

执行后,终端输出:

  1. ...
  2. "ScopeMetrics": [
  3. {
  4. "Scope": {
  5. "Name": "github.com/gogf/gf/example/metric/basic",
  6. "Version": "v1.0",
  7. "SchemaURL": ""
  8. },
  9. "Metrics": [
  10. {
  11. "Name": "goframe.metric.demo.counter",
  12. "Description": "This is a simple demo for Counter usage",
  13. "Unit": "bytes",
  14. "Data": {
  15. "DataPoints": [
  16. {
  17. "Attributes": [],
  18. "StartTime": "2024-03-25T10:13:19.326977+08:00",
  19. "Time": "2024-03-25T10:13:19.327144+08:00",
  20. "Value": 11
  21. }
  22. ],
  23. "Temporality": "CumulativeTemporality",
  24. "IsMonotonic": true
  25. }
  26. }
  27. ]
  28. },
  29. ...

为了简化示例介绍,我们在这里省略了一些输出内容,更详细的指标及输出介绍请参考后续章节。