Skip to content

Commit

Permalink
fixup! Stringify time.Time in format of RFC3339
Browse files Browse the repository at this point in the history
  • Loading branch information
ebi-yade committed Nov 28, 2024
1 parent db85cd4 commit 8f09627
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
19 changes: 19 additions & 0 deletions pkg/otel/attr.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,14 @@ func marshalField(f structFiled, fv reflect.Value) ([]attribute.KeyValue, error)
case reflect.Slice, reflect.Array:
return marshalSlice(f, fv)
case reflect.Struct:
// convert time.Time to string
if fv.Type().ConvertibleTo(timeType) {
return []attribute.KeyValue{
attribute.String(f.attributeName, fv.Interface().(time.Time).Format(time.RFC3339)),
}, nil
}

// delve into normal struct types
kvs, err := MarshalOtelAttributes(fv.Interface())
if err != nil {
return nil, err
Expand Down Expand Up @@ -229,6 +237,17 @@ func marshalSlice(f structFiled, fv reflect.Value) ([]attribute.KeyValue, error)
return []attribute.KeyValue{attribute.Float64Slice(f.attributeName, reflectValueToSlice[float64](fv))}, nil
case reflect.String:
return []attribute.KeyValue{attribute.StringSlice(f.attributeName, reflectValueToSlice[string](fv))}, nil
case reflect.Struct:
if fv.Type().Elem().ConvertibleTo(timeType) {
// TODO: consider reimplemeting it with samber/lo.Map
times := reflectValueToSlice[time.Time](fv)
strs := make([]string, len(times))
for i, t := range times {
strs[i] = t.Format(time.RFC3339)
}
return []attribute.KeyValue{attribute.StringSlice(f.attributeName, strs)}, nil
}
fallthrough
default:
bs, err := json.Marshal(fv.Interface())
if err != nil {
Expand Down
3 changes: 3 additions & 0 deletions pkg/otel/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package otel
import (
"reflect"
"sync"
"time"
)

type cache[T any] struct {
Expand All @@ -28,3 +29,5 @@ func (c *cache[T]) set(t reflect.Type, v T) {
c.cache[t] = v
c.mu.Unlock()
}

var timeType = reflect.TypeOf(time.Time{})

0 comments on commit 8f09627

Please sign in to comment.