Introduction

The code development of monitoring metrics directly uses the gmetric component of the main library of the framework. However, since the gmetric component actually only defines the relevant interfaces for monitoring metrics and provides the default NoopPerformer, the default monitoring metrics feature is turned off. Therefore, it is necessary to introduce specific interface implementation components to truly enable the monitoring metrics feature. The framework community provides the community component github.com/gogf/gf/contrib/metric/otelmetric/v2, which uses OpenTelemetry to implement the monitoring metrics interface of the framework. By introducing this community component and executing the creation of monitoring metrics management objects, the monitoring metrics feature can be enabled. The source code address of the otelmetric component: https://github.com/gogf/gf/tree/master/contrib/metric/otelmetric

We will introduce the basic usage of the monitoring metrics component through a simple monitoring metrics implementation example.

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

Creation of Metric Management Components

The global monitoring metric management object can be obtained through the gmetric.GetGlobalProvider() method. This object is a singleton design, and there can only be one globally. The Meter method of this object can be used to create/get the corresponding component object. The component object is used to manage all the monitoring metrics under this component. When creating a component object, it is usually necessary to define the name and version of the component (Instrument) (although it can also be empty, it is recommended to set it for easy maintenance in the future).

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

The gmeter.MeterOption data structure is as follows:

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

Creation of Monitoring Metric Objects

Through the Meter interface object, we can create the corresponding various metrics under this component. Metrics have various data types, so the definition of the Meter interface is as follows:

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

Taking the meter.MustCounter method used in this example code as an introduction, this method creates a Counter synchronous metric, and since we lazily use the Must* method, it means that if the creation of the metric fails, then this method will panic with an error. When creating a metric object, the metric name name is a required parameter, and the other MetricOption is optional, used to further describe the metric information. The data structure of MetricOption is defined as follows:

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

Initialization of Monitoring Metric Implementation

The creation and initialization of the monitoring metric management object can be done through the otelmetric.MustProvider creation method.

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

As introduced earlier, GlobalProvider is actually a singleton metric management object, so the provider.SetAsGlobal method call here can set the object as a global metric management object, which facilitates the subsequent creation of metrics based on this object.

We call the defer provider.ShutDown method in the main function to facilitate a graceful shutdown of the metric management object when the program ends, allowing, for example, the timely output of indicator caches to the target end.

Usage of Monitoring Metric Objects

Different metric objects have different operational methods for implementing changes in metric values. Taking the Counter metric type used in the example as an example, its interface is defined as follows:

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

As can be seen, the Counter metric can primarily perform two operation methods, Inc and Add. There is also a Metric interface, and all metrics implement this interface to obtain basic information of the current metric. The interface is defined as follows:

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

Data Reading of Monitoring Metrics

Through the OpenTelemetry component relationship introduced in the previous chapter, we know that if you want to use metrics, you must use a MetricReader. Therefore, in this example code, we use the most commonly used ManualReader in the open-source components of the OpenTelemetry official community to simply implement metric data reading. The ManualReader is provided by the OpenTelemetry official community.

  1. reader = metric.NewManualReader()

And configured to Provider through the WithReader method:

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

Then, the current metric data can be obtained through the Collect method:

  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)

After execution, the terminal output:

  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. ...

To simplify the example introduction, we have omitted some output contents here. For more detailed metric and output descriptions, please refer to the following chapters.