From 5a9dd890c912f9c0730b0ffdb497129c94ab2324 Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Tue, 26 Mar 2024 08:35:48 +0300 Subject: [PATCH] add support for context attrs funcs Signed-off-by: Vasiliy Tolstov --- zerolog.go | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/zerolog.go b/zerolog.go index 9622a16..76f6ae1 100644 --- a/zerolog.go +++ b/zerolog.go @@ -214,8 +214,17 @@ func (l *zeroLogger) Log(ctx context.Context, level logger.Level, args ...interf return } + var attrs []interface{} + for _, fn := range l.opts.Options.ContextAttrFuncs { + attrs = append(attrs, fn(ctx)...) + } + msg := fmt.Sprint(args...) - l.zLog.WithLevel(loggerToZerologLevel(level)).Msg(msg) + if len(attrs) > 0 { + l.zLog.WithLevel(loggerToZerologLevel(level)).Fields(attrs).Msg(msg) + } else { + l.zLog.WithLevel(loggerToZerologLevel(level)).Msg(msg) + } } func (l *zeroLogger) Logf(ctx context.Context, level logger.Level, format string, args ...interface{}) { @@ -223,7 +232,16 @@ func (l *zeroLogger) Logf(ctx context.Context, level logger.Level, format string return } - l.zLog.WithLevel(loggerToZerologLevel(level)).Msgf(format, args...) + var attrs []interface{} + for _, fn := range l.opts.Options.ContextAttrFuncs { + attrs = append(attrs, fn(ctx)...) + } + + if len(attrs) > 0 { + l.zLog.WithLevel(loggerToZerologLevel(level)).Fields(attrs).Msgf(format, args...) + } else { + l.zLog.WithLevel(loggerToZerologLevel(level)).Msgf(format, args...) + } } func (l *zeroLogger) String() string {