Skip to content

Commit

Permalink
log: add a way to get an io.Writer
Browse files Browse the repository at this point in the history
Add methods to create an io.Writer associated with a named logger.

Signed-off-by: Sergei Trofimov <[email protected]>
  • Loading branch information
setrofim committed Jul 19, 2023
1 parent cc09840 commit 2a2acce
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package log
import (
"bytes"
"fmt"
"io"
"sort"
"strings"
"text/template"
Expand Down Expand Up @@ -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...)
Expand Down

0 comments on commit 2a2acce

Please sign in to comment.