github.com/gogf/gf/v2@v2.7.4/os/gmetric/gmetric.go (about)

     1  // Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  // Package gmetric provides interface definitions and simple api for metric feature.
     8  package gmetric
     9  
    10  import (
    11  	"context"
    12  )
    13  
    14  // MetricType is the type of metric.
    15  type MetricType string
    16  
    17  const (
    18  	MetricTypeCounter                 MetricType = `Counter`                 // Counter.
    19  	MetricTypeUpDownCounter           MetricType = `UpDownCounter`           // UpDownCounter.
    20  	MetricTypeHistogram               MetricType = `Histogram`               // Histogram.
    21  	MetricTypeObservableCounter       MetricType = `ObservableCounter`       // ObservableCounter.
    22  	MetricTypeObservableUpDownCounter MetricType = `ObservableUpDownCounter` // ObservableUpDownCounter.
    23  	MetricTypeObservableGauge         MetricType = `ObservableGauge`         // ObservableGauge.
    24  )
    25  
    26  const (
    27  	// MetricNamePattern is the regular expression pattern for validating metric name.
    28  	MetricNamePattern = `[\w\.\-\/]`
    29  )
    30  
    31  // Provider manages all Metric exporting.
    32  // Be caution that the Histogram buckets could not be customized if the creation of the Histogram
    33  // is before the creation of Provider.
    34  type Provider interface {
    35  	// SetAsGlobal sets current provider as global meter provider for current process,
    36  	// which makes the following metrics creating on this Provider, especially the metrics created in runtime.
    37  	SetAsGlobal()
    38  
    39  	// MeterPerformer creates and returns the MeterPerformer that can produce kinds of metric Performer.
    40  	MeterPerformer(config MeterOption) MeterPerformer
    41  
    42  	// ForceFlush flushes all pending metrics.
    43  	//
    44  	// This method honors the deadline or cancellation of ctx. An appropriate
    45  	// error will be returned in these situations. There is no guaranteed that all
    46  	// metrics be flushed or all resources have been released in these situations.
    47  	ForceFlush(ctx context.Context) error
    48  
    49  	// Shutdown shuts down the Provider flushing all pending metrics and
    50  	// releasing any held computational resources.
    51  	Shutdown(ctx context.Context) error
    52  }
    53  
    54  // MeterPerformer manages all Metric performers creating.
    55  type MeterPerformer interface {
    56  	// CounterPerformer creates and returns a CounterPerformer that performs
    57  	// the operations for Counter metric.
    58  	CounterPerformer(name string, option MetricOption) (CounterPerformer, error)
    59  
    60  	// UpDownCounterPerformer creates and returns a UpDownCounterPerformer that performs
    61  	// the operations for UpDownCounter metric.
    62  	UpDownCounterPerformer(name string, option MetricOption) (UpDownCounterPerformer, error)
    63  
    64  	// HistogramPerformer creates and returns a HistogramPerformer that performs
    65  	// the operations for Histogram metric.
    66  	HistogramPerformer(name string, option MetricOption) (HistogramPerformer, error)
    67  
    68  	// ObservableCounterPerformer creates and returns an ObservableCounterPerformer that performs
    69  	// the operations for ObservableCounter metric.
    70  	ObservableCounterPerformer(name string, option MetricOption) (ObservableCounterPerformer, error)
    71  
    72  	// ObservableUpDownCounterPerformer creates and returns an ObservableUpDownCounterPerformer that performs
    73  	// the operations for ObservableUpDownCounter metric.
    74  	ObservableUpDownCounterPerformer(name string, option MetricOption) (ObservableUpDownCounterPerformer, error)
    75  
    76  	// ObservableGaugePerformer creates and returns an ObservableGaugePerformer that performs
    77  	// the operations for ObservableGauge metric.
    78  	ObservableGaugePerformer(name string, option MetricOption) (ObservableGaugePerformer, error)
    79  
    80  	// RegisterCallback registers callback on certain metrics.
    81  	// A callback is bound to certain component and version, it is called when the associated metrics are read.
    82  	// Multiple callbacks on the same component and version will be called by their registered sequence.
    83  	RegisterCallback(callback Callback, canBeCallbackMetrics ...ObservableMetric) error
    84  }
    85  
    86  // MetricOption holds the basic options for creating a metric.
    87  type MetricOption struct {
    88  	// Help provides information about this Histogram.
    89  	// This is an optional configuration for a metric.
    90  	Help string
    91  
    92  	// Unit is the unit for metric value.
    93  	// This is an optional configuration for a metric.
    94  	Unit string
    95  
    96  	// Attributes holds the constant key-value pair description metadata for this metric.
    97  	// This is an optional configuration for a metric.
    98  	Attributes Attributes
    99  
   100  	// Buckets defines the buckets into which observations are counted.
   101  	// For Histogram metric only.
   102  	// A histogram metric uses default buckets if no explicit buckets configured.
   103  	Buckets []float64
   104  
   105  	// Callback function for metric, which is called when metric value changes.
   106  	// For observable metric only.
   107  	// If an observable metric has either Callback attribute nor global callback configured, it does nothing.
   108  	Callback MetricCallback
   109  }
   110  
   111  // Metric models a single sample value with its metadata being exported.
   112  type Metric interface {
   113  	// Info returns the basic information of a Metric.
   114  	Info() MetricInfo
   115  }
   116  
   117  // MetricInfo exports information of the Metric.
   118  type MetricInfo interface {
   119  	Key() string                // Key returns the unique string key of the metric.
   120  	Name() string               // Name returns the name of the metric.
   121  	Help() string               // Help returns the help description of the metric.
   122  	Unit() string               // Unit returns the unit name of the metric.
   123  	Type() MetricType           // Type returns the type of the metric.
   124  	Attributes() Attributes     // Attributes returns the constant attribute slice of the metric.
   125  	Instrument() InstrumentInfo // InstrumentInfo returns the instrument info of the metric.
   126  }
   127  
   128  // InstrumentInfo exports the instrument information of a metric.
   129  type InstrumentInfo interface {
   130  	Name() string    // Name returns the instrument name of the metric.
   131  	Version() string // Version returns the instrument version of the metric.
   132  }
   133  
   134  // Counter is a Metric that represents a single numerical value that can ever
   135  // goes up.
   136  type Counter interface {
   137  	Metric
   138  	CounterPerformer
   139  }
   140  
   141  // CounterPerformer performs operations for Counter metric.
   142  type CounterPerformer interface {
   143  	// Inc increments the counter by 1. Use Add to increment it by arbitrary
   144  	// non-negative values.
   145  	Inc(ctx context.Context, option ...Option)
   146  
   147  	// Add adds the given value to the counter. It panics if the value is < 0.
   148  	Add(ctx context.Context, increment float64, option ...Option)
   149  }
   150  
   151  // UpDownCounter is a Metric that represents a single numerical value that can ever
   152  // goes up or down.
   153  type UpDownCounter interface {
   154  	Metric
   155  	UpDownCounterPerformer
   156  }
   157  
   158  // UpDownCounterPerformer performs operations for UpDownCounter metric.
   159  type UpDownCounterPerformer interface {
   160  	// Inc increments the counter by 1. Use Add to increment it by arbitrary
   161  	// non-negative values.
   162  	Inc(ctx context.Context, option ...Option)
   163  
   164  	// Dec decrements the Gauge by 1. Use Sub to decrement it by arbitrary values.
   165  	Dec(ctx context.Context, option ...Option)
   166  
   167  	// Add adds the given value to the counter. It panics if the value is < 0.
   168  	Add(ctx context.Context, increment float64, option ...Option)
   169  }
   170  
   171  // Histogram counts individual observations from an event or sample stream in
   172  // configurable static buckets (or in dynamic sparse buckets as part of the
   173  // experimental Native Histograms, see below for more details). Similar to a
   174  // Summary, it also provides a sum of observations and an observation count.
   175  type Histogram interface {
   176  	Metric
   177  	HistogramPerformer
   178  
   179  	// Buckets returns the bucket slice of the Histogram.
   180  	Buckets() []float64
   181  }
   182  
   183  // HistogramPerformer performs operations for Histogram metric.
   184  type HistogramPerformer interface {
   185  	// Record adds a single value to the histogram.
   186  	// The value is usually positive or zero.
   187  	Record(increment float64, option ...Option)
   188  }
   189  
   190  // ObservableCounter is an instrument used to asynchronously
   191  // record float64 measurements once per collection cycle. Observations are only
   192  // made within a callback for this instrument. The value observed is assumed
   193  // the to be the cumulative sum of the count.
   194  type ObservableCounter interface {
   195  	Metric
   196  	ObservableCounterPerformer
   197  }
   198  
   199  // ObservableUpDownCounter is used to synchronously record float64 measurements during a computational
   200  // operation.
   201  type ObservableUpDownCounter interface {
   202  	Metric
   203  	ObservableUpDownCounterPerformer
   204  }
   205  
   206  // ObservableGauge is an instrument used to asynchronously record
   207  // instantaneous float64 measurements once per collection cycle. Observations
   208  // are only made within a callback for this instrument.
   209  type ObservableGauge interface {
   210  	Metric
   211  	ObservableGaugePerformer
   212  }
   213  
   214  type (
   215  	// ObservableCounterPerformer is performer for observable ObservableCounter.
   216  	ObservableCounterPerformer = ObservableMetric
   217  
   218  	// ObservableUpDownCounterPerformer is performer for observable ObservableUpDownCounter.
   219  	ObservableUpDownCounterPerformer = ObservableMetric
   220  
   221  	// ObservableGaugePerformer is performer for observable ObservableGauge.
   222  	ObservableGaugePerformer = ObservableMetric
   223  )
   224  
   225  // ObservableMetric is an instrument used to asynchronously record
   226  // instantaneous float64 measurements once per collection cycle.
   227  type ObservableMetric interface {
   228  	observable()
   229  }
   230  
   231  // MetricInitializer manages the initialization for Metric.
   232  // It is called internally in metric interface implements.
   233  type MetricInitializer interface {
   234  	// Init initializes the Metric in Provider creation.
   235  	// It sets the metric performer which really takes action.
   236  	Init(provider Provider) error
   237  }
   238  
   239  // PerformerExporter exports internal Performer of Metric.
   240  // It is called internally in metric interface implements.
   241  type PerformerExporter interface {
   242  	// Performer exports internal Performer of Metric.
   243  	// This is usually used by metric implements.
   244  	Performer() any
   245  }
   246  
   247  // MetricCallback is automatically called when metric reader starts reading the metric value.
   248  type MetricCallback func(ctx context.Context, obs MetricObserver) error
   249  
   250  // Callback is a function registered with a Meter that makes observations for
   251  // the set of instruments it is registered with. The Observer parameter is used
   252  // to record measurement observations for these instruments.
   253  type Callback func(ctx context.Context, obs Observer) error
   254  
   255  // Observer sets the value for certain initialized Metric.
   256  type Observer interface {
   257  	// Observe observes the value for certain initialized Metric.
   258  	// It adds the value to total result if the observed Metrics is type of Counter.
   259  	// It sets the value as the result if the observed Metrics is type of Gauge.
   260  	Observe(m ObservableMetric, value float64, option ...Option)
   261  }
   262  
   263  // MetricObserver sets the value for bound Metric.
   264  type MetricObserver interface {
   265  	// Observe observes the value for certain initialized Metric.
   266  	// It adds the value to total result if the observed Metrics is type of Counter.
   267  	// It sets the value as the result if the observed Metrics is type of Gauge.
   268  	Observe(value float64, option ...Option)
   269  }
   270  
   271  var (
   272  	// metrics stores all created Metric by current package.
   273  	allMetrics = make([]Metric, 0)
   274  )
   275  
   276  // IsEnabled returns whether the metrics feature is enabled.
   277  func IsEnabled() bool {
   278  	return globalProvider != nil
   279  }
   280  
   281  // GetAllMetrics returns all Metric that created by current package.
   282  func GetAllMetrics() []Metric {
   283  	return allMetrics
   284  }