github.com/asynkron/protoactor-go@v0.0.0-20240308120642-ef91a6abee75/metrics/metrics.go (about) 1 // Copyright (C) 2017 - 2022 Asynkron.se <http://www.asynkron.se> 2 3 package metrics 4 5 import ( 6 "fmt" 7 "log/slog" 8 "sync" 9 ) 10 11 const InternalActorMetrics string = "internal.actor.metrics" 12 13 type ProtoMetrics struct { 14 mu sync.Mutex 15 actorMetrics *ActorMetrics 16 knownMetrics map[string]*ActorMetrics 17 logger *slog.Logger 18 } 19 20 func NewProtoMetrics(logger *slog.Logger) *ProtoMetrics { 21 protoMetrics := ProtoMetrics{ 22 actorMetrics: NewActorMetrics(logger), 23 knownMetrics: make(map[string]*ActorMetrics), 24 logger: logger, 25 } 26 27 protoMetrics.Register(InternalActorMetrics, protoMetrics.actorMetrics) 28 return &protoMetrics 29 } 30 31 func (pm *ProtoMetrics) Instruments() *ActorMetrics { return pm.actorMetrics } 32 33 func (pm *ProtoMetrics) Register(key string, instance *ActorMetrics) { 34 pm.mu.Lock() 35 defer pm.mu.Unlock() 36 logger := pm.logger 37 38 if _, ok := pm.knownMetrics[key]; ok { 39 err := fmt.Errorf("could not register instance %#v of metrics, %s already registered", instance, key) 40 logger.Error(err.Error(), slog.Any("error", err)) 41 return 42 } 43 44 pm.knownMetrics[key] = instance 45 } 46 47 func (pm *ProtoMetrics) Get(key string) *ActorMetrics { 48 metrics, ok := pm.knownMetrics[key] 49 if !ok { 50 logger := pm.logger 51 err := fmt.Errorf("unknown metrics for the given %s key", key) 52 logger.Error(err.Error(), slog.Any("error", err)) 53 return nil 54 } 55 56 return metrics 57 }