package observ
import (
"context"
"fmt"
"sync"
"sync/atomic"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/sdk"
"go.opentelemetry.io/otel/sdk/log/internal/x"
semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
"go.opentelemetry.io/otel/semconv/v1.40.0/otelconv"
)
const (
ScopeName = "go.opentelemetry.io/otel/sdk/log/internal/observ"
)
var measureAttrsPool = sync .Pool {
New : func () any {
const n = 1 + 1 + 1
s := make ([]attribute .KeyValue , 0 , n )
return &s
},
}
var simpleProcessorN atomic .Int64
func NextSimpleProcessorID () int64 {
const inc = 1
return simpleProcessorN .Add (inc ) - inc
}
func SetSimpleProcessorID (v int64 ) int64 {
return simpleProcessorN .Swap (v )
}
func GetSLPComponentName (id int64 ) attribute .KeyValue {
t := otelconv .ComponentTypeSimpleLogProcessor
name := fmt .Sprintf ("%s/%d" , t , id )
return semconv .OTelComponentName (name )
}
type SLP struct {
processed metric .Int64Counter
attrs []attribute .KeyValue
addOpts []metric .AddOption
}
func NewSLP (id int64 ) (*SLP , error ) {
if !x .Observability .Enabled () {
return nil , nil
}
meter := otel .GetMeterProvider ()
mt := meter .Meter (
ScopeName ,
metric .WithInstrumentationVersion (sdk .Version ()),
metric .WithSchemaURL (semconv .SchemaURL ),
)
p , err := otelconv .NewSDKProcessorLogProcessed (mt )
if err != nil {
err = fmt .Errorf ("failed to create a processed log metric: %w" , err )
return nil , err
}
name := GetSLPComponentName (id )
componentType := p .AttrComponentType (otelconv .ComponentTypeSimpleLogProcessor )
attrs := []attribute .KeyValue {name , componentType }
addOpts := []metric .AddOption {metric .WithAttributeSet (attribute .NewSet (attrs ...))}
return &SLP {
processed : p .Inst (),
attrs : attrs ,
addOpts : addOpts ,
}, nil
}
func (slp *SLP ) LogProcessed (ctx context .Context , err error ) {
if slp .processed .Enabled (ctx ) {
slp .processed .Add (ctx , 1 , slp .addOption (err )...)
}
}
func (slp *SLP ) addOption (err error ) []metric .AddOption {
if err == nil {
return slp .addOpts
}
attrs := measureAttrsPool .Get ().(*[]attribute .KeyValue )
defer func () {
*attrs = (*attrs )[:0 ]
measureAttrsPool .Put (attrs )
}()
*attrs = append (*attrs , slp .attrs ...)
*attrs = append (*attrs , semconv .ErrorType (err ))
return []metric .AddOption {metric .WithAttributeSet (attribute .NewSet (*attrs ...))}
}
The pages are generated with Golds v0.8.2 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .