forked from mtusi2026/mtusi2026lab6
feat: add OpenTelemetry instrumentation
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
)
|
||||
|
||||
type MessageCarrier struct {
|
||||
Traceparent string
|
||||
Tracestate string
|
||||
}
|
||||
|
||||
func Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context {
|
||||
return otel.GetTextMapPropagator().Extract(ctx, carrier)
|
||||
}
|
||||
|
||||
func Inject(ctx context.Context, carrier propagation.TextMapCarrier) {
|
||||
otel.GetTextMapPropagator().Inject(ctx, carrier)
|
||||
}
|
||||
|
||||
func ContextCarrier(ctx context.Context) MessageCarrier {
|
||||
carrier := propagation.MapCarrier{}
|
||||
Inject(ctx, carrier)
|
||||
return MessageCarrier{
|
||||
Traceparent: carrier.Get("traceparent"),
|
||||
Tracestate: carrier.Get("tracestate"),
|
||||
}
|
||||
}
|
||||
|
||||
func ExtractMessage(ctx context.Context, carrier MessageCarrier) context.Context {
|
||||
headers := propagation.MapCarrier{
|
||||
"traceparent": carrier.Traceparent,
|
||||
"tracestate": carrier.Tracestate,
|
||||
}
|
||||
return Extract(ctx, headers)
|
||||
}
|
||||
|
||||
func ExtractJSONMessage(ctx context.Context, payload []byte) context.Context {
|
||||
var carrier struct {
|
||||
Traceparent string `json:"traceparent"`
|
||||
Tracestate string `json:"tracestate"`
|
||||
}
|
||||
if json.Unmarshal(payload, &carrier) != nil {
|
||||
return ctx
|
||||
}
|
||||
return ExtractMessage(ctx, MessageCarrier(carrier))
|
||||
}
|
||||
|
||||
func InjectJSONMessage(ctx context.Context, payload []byte) ([]byte, error) {
|
||||
var value map[string]json.RawMessage
|
||||
if err := json.Unmarshal(payload, &value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
carrier := ContextCarrier(ctx)
|
||||
setJSONField(value, "traceparent", carrier.Traceparent)
|
||||
setJSONField(value, "tracestate", carrier.Tracestate)
|
||||
return json.Marshal(value)
|
||||
}
|
||||
|
||||
func setJSONField(value map[string]json.RawMessage, key, field string) {
|
||||
if field == "" {
|
||||
delete(value, key)
|
||||
return
|
||||
}
|
||||
encoded, _ := json.Marshal(field)
|
||||
value[key] = encoded
|
||||
}
|
||||
Reference in New Issue
Block a user