From 84cd34032c3a93bbac6b2c94b9c725f68715134f Mon Sep 17 00:00:00 2001 From: Steve Jones Date: Fri, 3 Nov 2023 10:35:00 -0700 Subject: [PATCH] zapslog: Handler options modification via WithOptions --- exp/zapslog/handler.go | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/exp/zapslog/handler.go b/exp/zapslog/handler.go index 982d9bccd..0cde902c5 100644 --- a/exp/zapslog/handler.go +++ b/exp/zapslog/handler.go @@ -48,10 +48,7 @@ func NewHandler(core zapcore.Core, opts ...Option) *Handler { core: core, addStackAt: slog.LevelError, } - for _, v := range opts { - v.apply(h) - } - return h + return h.WithOptions(opts...) } var _ slog.Handler = (*Handler)(nil) @@ -182,9 +179,23 @@ func (h *Handler) WithGroup(group string) slog.Handler { return h.withFields(zap.Namespace(group)) } +// WithOptions returns a new Handler with the given options. +func (h *Handler) WithOptions(opts ...Option) *Handler { + cloned := h.clone() + for _, v := range opts { + v.apply(cloned) + } + return cloned +} + // withFields returns a cloned Handler with the given fields. func (h *Handler) withFields(fields ...zapcore.Field) *Handler { - cloned := *h + cloned := h.clone() cloned.core = h.core.With(fields) + return cloned +} + +func (h *Handler) clone() *Handler { + cloned := *h return &cloned }