From 2a2acce991b5b3720b151f7841fbdc66eca95bb6 Mon Sep 17 00:00:00 2001 From: Sergei Trofimov Date: Wed, 5 Jul 2023 14:31:44 +0100 Subject: [PATCH] log: add a way to get an io.Writer Add methods to create an io.Writer associated with a named logger. Signed-off-by: Sergei Trofimov --- log/log.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/log/log.go b/log/log.go index a0d98449..d366f369 100644 --- a/log/log.go +++ b/log/log.go @@ -5,6 +5,7 @@ package log import ( "bytes" "fmt" + "io" "sort" "strings" "text/template" @@ -283,6 +284,50 @@ func Named(name string) *zap.SugaredLogger { return logger.Named(name) } +// NamedWriter creates an io.Writer that utilizes a zap logger with the +// specified name at the specifed level. +func NamedWriter(name string, level zapcore.Level) io.Writer { + return WriterFromZap(Named(name), level) +} + +type logWriter struct { + write func(args ...interface{}) +} + +func (o logWriter) Write(p []byte) (int, error) { + o.write(strings.TrimSuffix(string(p), "\n")) + return len(p), nil +} + +const ( + DebugLevel = zap.DebugLevel + TraceLevel = zap.DebugLevel + InfoLevel = zap.InfoLevel + WarnLevel = zap.WarnLevel + ErrorLevel = zap.ErrorLevel +) + +// WriterFromZap returns an io.Writer utilzing the provided zap logger at the +// specified level. +func WriterFromZap(logger *zap.SugaredLogger, level zapcore.Level) io.Writer { + var writeFunc func(args ...interface{}) + + switch level { + case zapcore.DebugLevel: + writeFunc = logger.Debug + case zapcore.InfoLevel: + writeFunc = logger.Info + case zapcore.WarnLevel: + writeFunc = logger.Warn + case zapcore.ErrorLevel: + writeFunc = logger.Error + default: + panic(fmt.Sprintf("unexpected level name: %q", level)) + } + + return logWriter{writeFunc} +} + // Debug uses fmt.Sprint to construct and log a message. func Debug(args ...interface{}) { logger.Debug(args...)