Skip to content

Commit

Permalink
Merge pull request #4 from go-logr/wip
Browse files Browse the repository at this point in the history
Support logr.Marshaler and fmt.Stringer
  • Loading branch information
thockin committed Oct 21, 2021
2 parents f9ef809 + 10545b4 commit 5a64b15
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion zerologr.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
package zerologr

import (
"fmt"

"github.com/go-logr/logr"
"github.com/rs/zerolog"
)
Expand All @@ -31,6 +33,12 @@ var (
NameFieldName = "logger"
// NameSeparator separates names for logr.WithName
NameSeparator = "/"

// RenderArgsHook mutates the list of key-value pairs passed directly to Info and Error.
RenderArgsHook = DefaultRender

// RenderValuesHook mutates the list of key-value pairs saved via WithValues.
RenderValuesHook = DefaultRender
)

// Logger is type alias of logr.Logger
Expand Down Expand Up @@ -102,13 +110,19 @@ func (ls *LogSink) msg(e *zerolog.Event, msg string, keysAndValues []interface{}
if ls.name != "" {
e.Str(NameFieldName, ls.name)
}
if RenderArgsHook != nil {
keysAndValues = RenderArgsHook(keysAndValues)
}
e = e.Fields(keysAndValues)
e.CallerSkipFrame(int(ls.depth))
e.CallerSkipFrame(ls.depth)
e.Msg(msg)
}

// WithValues returns a new LogSink with additional key/value pairs.
func (ls LogSink) WithValues(keysAndValues ...interface{}) logr.LogSink {
if RenderValuesHook != nil {
keysAndValues = RenderValuesHook(keysAndValues)
}
l := ls.l.With().Fields(keysAndValues).Logger()
ls.l = &l
return &ls
Expand All @@ -135,3 +149,17 @@ func (ls LogSink) WithCallDepth(depth int) logr.LogSink {
func (ls *LogSink) GetUnderlying() *zerolog.Logger {
return ls.l
}

// DefaultRender supports logr.Marshaler and fmt.Stringer.
func DefaultRender(keysAndValues []interface{}) []interface{} {
for i, n := 1, len(keysAndValues); i < n; i += 2 {
value := keysAndValues[i]
switch v := value.(type) {
case logr.Marshaler:
keysAndValues[i] = v.MarshalLog()
case fmt.Stringer:
keysAndValues[i] = v.String()
}
}
return keysAndValues
}

0 comments on commit 5a64b15

Please sign in to comment.