Skip to content

Commit

Permalink
add proto/time/duration slice loggers (#842)
Browse files Browse the repository at this point in the history
  • Loading branch information
paulwe authored Oct 8, 2024
1 parent fbcc09c commit b2c7ca3
Showing 1 changed file with 45 additions and 2 deletions.
47 changes: 45 additions & 2 deletions logger/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,33 @@
package logger

import (
"time"

"go.uber.org/multierr"
"go.uber.org/zap/zapcore"
"google.golang.org/protobuf/proto"
)

func ObjectSlice[T zapcore.ObjectMarshaler](s []T) zapcore.ArrayMarshaler {
return objectSlice[T](s)
type protoSlice[T proto.Message] []T

func ProtoSlice[T proto.Message](s []T) zapcore.ArrayMarshaler {
return protoSlice[T](s)
}

func (s protoSlice[T]) MarshalLogArray(e zapcore.ArrayEncoder) error {
var err error
for _, v := range s {
err = multierr.Append(err, e.AppendObject(Proto(v)))
}
return err
}

type objectSlice[T zapcore.ObjectMarshaler] []T

func ObjectSlice[T zapcore.ObjectMarshaler](s []T) zapcore.ArrayMarshaler {
return objectSlice[T](s)
}

func (s objectSlice[T]) MarshalLogArray(e zapcore.ArrayEncoder) error {
var err error
for _, v := range s {
Expand All @@ -33,6 +50,32 @@ func (s objectSlice[T]) MarshalLogArray(e zapcore.ArrayEncoder) error {
return err
}

type timeSlice []time.Time

func TimeSlice(s []time.Time) zapcore.ArrayMarshaler {
return timeSlice(s)
}

func (s timeSlice) MarshalLogArray(e zapcore.ArrayEncoder) error {
for _, v := range s {
e.AppendTime(v)
}
return nil
}

type durationSlice []time.Duration

func DurationSlice(s []time.Duration) zapcore.ArrayMarshaler {
return durationSlice(s)
}

func (s durationSlice) MarshalLogArray(e zapcore.ArrayEncoder) error {
for _, v := range s {
e.AppendDuration(v)
}
return nil
}

type boolSlice[T ~bool] []T

func BoolSlice[T ~bool](s []T) zapcore.ArrayMarshaler {
Expand Down

0 comments on commit b2c7ca3

Please sign in to comment.