From b2c7ca3114ae1833e6e1efd317a1f8d0797c74d0 Mon Sep 17 00:00:00 2001 From: Paul Wells Date: Tue, 8 Oct 2024 04:07:13 -0700 Subject: [PATCH] add proto/time/duration slice loggers (#842) --- logger/slice.go | 47 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/logger/slice.go b/logger/slice.go index 49ab6d8e..ddf959ee 100644 --- a/logger/slice.go +++ b/logger/slice.go @@ -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 { @@ -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 {