Skip to content

Commit

Permalink
feat: support customization of json marshal
Browse files Browse the repository at this point in the history
  • Loading branch information
lilasxie committed Nov 10, 2023
1 parent 7208905 commit f029c91
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 12 deletions.
14 changes: 14 additions & 0 deletions log/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,20 @@ func NewLogger(dst io.Writer, options ...Option) Logger {
for _, opt := range options {
opt(&logCfg)
}
if logCfg.JSONMarshal != nil {
zerolog.InterfaceMarshalFunc = func(i interface{}) ([]byte, error) {
switch v := i.(type) {
case json.Marshaler:
return logCfg.JSONMarshal(i)
case encoding.TextMarshaler:
return logCfg.JSONMarshal(i)
case fmt.Stringer:
return logCfg.JSONMarshal(v.String())
default:
return logCfg.JSONMarshal(i)
}
}
}

output := dst
if !logCfg.OutputJSON {
Expand Down
34 changes: 22 additions & 12 deletions log/options.go
Original file line number Diff line number Diff line change
@@ -1,29 +1,32 @@
package log

import (
"encoding/json"
"time"

"github.com/rs/zerolog"
)

// defaultConfig has all the options disabled, except Color and TimeFormat
var defaultConfig = Config{
Level: zerolog.NoLevel,
Filter: nil,
OutputJSON: false,
Color: true,
StackTrace: false,
TimeFormat: time.Kitchen,
Level: zerolog.NoLevel,
Filter: nil,
OutputJSON: false,
Color: true,
StackTrace: false,
TimeFormat: time.Kitchen,
JSONMarshal: json.Marshal,
}

// Config defines configuration for the logger.
type Config struct {
Level zerolog.Level
Filter FilterFunc
OutputJSON bool
Color bool
StackTrace bool
TimeFormat string
Level zerolog.Level
Filter FilterFunc
OutputJSON bool
Color bool
StackTrace bool
TimeFormat string
JSONMarshal func(v interface{}) ([]byte, error)
}

type Option func(*Config)
Expand Down Expand Up @@ -87,3 +90,10 @@ func TraceOption(val bool) Option {
cfg.StackTrace = val
}
}

// JSONMarshalOption add option to configure custom JSON encoding
func JSONMarshalOption(f func(v interface{}) ([]byte, error)) Option {
return func(cfg *Config) {
cfg.JSONMarshal = f
}
}

0 comments on commit f029c91

Please sign in to comment.