github.com/asynkron/protoactor-go@v0.0.0-20240308120642-ef91a6abee75/actor/metrics.go (about) 1 // Copyright (C) 2017 - 2022 Asynkron.se <http://www.asynkron.se> 2 3 package actor 4 5 import ( 6 "fmt" 7 "log/slog" 8 "strings" 9 10 "github.com/asynkron/protoactor-go/extensions" 11 "github.com/asynkron/protoactor-go/metrics" 12 "go.opentelemetry.io/otel" 13 "go.opentelemetry.io/otel/attribute" 14 "go.opentelemetry.io/otel/metric" 15 ) 16 17 var extensionId = extensions.NextExtensionID() 18 19 type Metrics struct { 20 metrics *metrics.ProtoMetrics 21 enabled bool 22 actorSystem *ActorSystem 23 } 24 25 var _ extensions.Extension = &Metrics{} 26 27 func (m *Metrics) Enabled() bool { 28 return m.enabled 29 } 30 31 func (m *Metrics) ExtensionID() extensions.ExtensionID { 32 return extensionId 33 } 34 35 func NewMetrics(system *ActorSystem, provider metric.MeterProvider) *Metrics { 36 if provider == nil { 37 return &Metrics{} 38 } 39 40 return &Metrics{ 41 metrics: metrics.NewProtoMetrics(system.Logger()), 42 enabled: true, 43 actorSystem: system, 44 } 45 } 46 47 func (m *Metrics) PrepareMailboxLengthGauge() { 48 meter := otel.Meter(metrics.LibName) 49 gauge, err := meter.Int64ObservableGauge("protoactor_actor_mailbox_length", 50 metric.WithDescription("Actor's Mailbox Length"), 51 metric.WithUnit("1")) 52 if err != nil { 53 err = fmt.Errorf("failed to create ActorMailBoxLength instrument, %w", err) 54 m.actorSystem.Logger().Error(err.Error(), slog.Any("error", err)) 55 } 56 m.metrics.Instruments().SetActorMailboxLengthGauge(gauge) 57 } 58 59 func (m *Metrics) CommonLabels(ctx Context) []attribute.KeyValue { 60 labels := []attribute.KeyValue{ 61 attribute.String("address", ctx.ActorSystem().Address()), 62 attribute.String("actortype", strings.Replace(fmt.Sprintf("%T", ctx.Actor()), "*", "", 1)), 63 } 64 65 return labels 66 }