github.com/gogf/gf/v2@v2.7.4/os/gmetric/gmetric_meter_callback.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
     8  
     9  // CallbackItem is the global callback item registered.
    10  type CallbackItem struct {
    11  	Callback    Callback           // Global callback.
    12  	Metrics     []ObservableMetric // Callback on certain metrics.
    13  	MeterOption MeterOption        // MeterOption is the option that the meter holds.
    14  	Provider    Provider           // Provider is the Provider that the callback item is bound to.
    15  }
    16  
    17  var (
    18  	// Registered callbacks.
    19  	globalCallbackItems = make([]CallbackItem, 0)
    20  )
    21  
    22  // RegisterCallback registers callback on certain metrics.
    23  // A callback is bound to certain component and version, it is called when the associated metrics are read.
    24  // Multiple callbacks on the same component and version will be called by their registered sequence.
    25  func (meter *localMeter) RegisterCallback(callback Callback, observableMetrics ...ObservableMetric) error {
    26  	if len(observableMetrics) == 0 {
    27  		return nil
    28  	}
    29  	globalCallbackItems = append(globalCallbackItems, CallbackItem{
    30  		Callback:    callback,
    31  		Metrics:     observableMetrics,
    32  		MeterOption: meter.MeterOption,
    33  	})
    34  	return nil
    35  }
    36  
    37  // MustRegisterCallback performs as RegisterCallback, but it panics if any error occurs.
    38  func (meter *localMeter) MustRegisterCallback(callback Callback, observableMetrics ...ObservableMetric) {
    39  	err := meter.RegisterCallback(callback, observableMetrics...)
    40  	if err != nil {
    41  		panic(err)
    42  	}
    43  }
    44  
    45  // GetRegisteredCallbacks retrieves and returns the registered global callbacks.
    46  // It truncates the callback slice is the callbacks are returned.
    47  func GetRegisteredCallbacks() []CallbackItem {
    48  	items := globalCallbackItems
    49  	globalCallbackItems = globalCallbackItems[:0]
    50  	return items
    51  }