From b415a60cd9e478c4f35b548cd74281e37cd702de Mon Sep 17 00:00:00 2001 From: Ian Shim Date: Tue, 26 Mar 2024 18:10:16 -0700 Subject: [PATCH] add With method to logger --- logging/logger.go | 2 ++ logging/noop_logger.go | 4 ++++ logging/slog_logger.go | 6 ++++++ logging/zap_logger.go | 6 ++++++ 4 files changed, 18 insertions(+) diff --git a/logging/logger.go b/logging/logger.go index d487890c..1913cff2 100644 --- a/logging/logger.go +++ b/logging/logger.go @@ -20,4 +20,6 @@ type Logger interface { Errorf(template string, args ...interface{}) Fatalf(template string, args ...interface{}) + + With(tags ...any) Logger } diff --git a/logging/noop_logger.go b/logging/noop_logger.go index 740ada6f..7af1db0b 100644 --- a/logging/noop_logger.go +++ b/logging/noop_logger.go @@ -37,3 +37,7 @@ func (l *NoopLogger) Warnf(template string, args ...interface{}) {} func (l *NoopLogger) Errorf(template string, args ...interface{}) {} func (l *NoopLogger) Fatalf(template string, args ...interface{}) {} + +func (l *NoopLogger) With(tags ...any) Logger { + return l +} diff --git a/logging/slog_logger.go b/logging/slog_logger.go index b0bf4733..f9385a08 100644 --- a/logging/slog_logger.go +++ b/logging/slog_logger.go @@ -106,3 +106,9 @@ func (s SLogger) logfCorrectSource(level slog.Level, template string, args ...in r := slog.NewRecord(time.Now(), level, fmt.Sprintf(template, args...), pcs[0]) _ = s.Handler().Handle(context.Background(), r) } + +func (s SLogger) With(tags ...any) Logger { + return &SLogger{ + s.Logger.With(tags...), + } +} diff --git a/logging/zap_logger.go b/logging/zap_logger.go index 22573e0f..5a4a0a73 100644 --- a/logging/zap_logger.go +++ b/logging/zap_logger.go @@ -80,3 +80,9 @@ func (z *ZapLogger) Errorf(template string, args ...interface{}) { func (z *ZapLogger) Fatalf(template string, args ...interface{}) { z.logger.Sugar().Fatalf(template, args...) } + +func (z *ZapLogger) With(tags ...any) Logger { + return &ZapLogger{ + logger: z.logger.Sugar().With(tags...).Desugar(), + } +}