Skip to content

Commit

Permalink
feat(otelx): nullable attribute helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
zepatrik committed Sep 12, 2024
1 parent 0516cf9 commit 06974cc
Showing 1 changed file with 42 additions and 1 deletion.
43 changes: 42 additions & 1 deletion otelx/attribute.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@

package otelx

import "go.opentelemetry.io/otel/attribute"
import (
"database/sql"
"fmt"

"go.opentelemetry.io/otel/attribute"
)

func StringAttrs(attrs map[string]string) []attribute.KeyValue {
s := []attribute.KeyValue{}
Expand All @@ -12,3 +17,39 @@ func StringAttrs(attrs map[string]string) []attribute.KeyValue {
}
return s
}

func AutoInt[I int | int32 | int64](k string, v I) attribute.KeyValue {
// Internally, the OpenTelemetry SDK uses int64 for all integer values anyway.
return attribute.Int64(k, int64(v))
}

func Nullable[V any, VN *V | sql.Null[V], A func(string, V) attribute.KeyValue](a A, k string, v VN) attribute.KeyValue {
switch v := any(v).(type) {
case *V:
if v == nil {
return attribute.String(k, "<nil>")
}
return a(k, *v)
case sql.Null[V]:
if !v.Valid {
return attribute.String(k, "<nil>")
}
return a(k, v.V)
}
return attribute.String(k, "unsupported type")
}

func NullString[V *string | sql.Null[string]](k string, v V) attribute.KeyValue {
return Nullable(attribute.String, k, v)
}

func NullStringer(k string, v fmt.Stringer) attribute.KeyValue {
if v == nil {
return attribute.String(k, "<nil>")
}
return attribute.String(k, v.String())
}

func NullInt[I int | int32 | int64, V *I | sql.Null[I]](k string, v V) attribute.KeyValue {
return Nullable[I](AutoInt, k, v)
}

0 comments on commit 06974cc

Please sign in to comment.