Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ type Config struct {
// See Open for details.
Output []string `mapstructure:"output"`

Format string `mapstructure:"format"`

// ErrorOutput is a list of URLs to write internal logger errors to.
// The default is standard error.
//
Expand Down Expand Up @@ -194,6 +196,19 @@ func (cfg *Config) BuildLogger() (*zap.Logger, error) {
zCfg.Encoding = cfg.Encoding
}

if cfg.Format != "" {
err := zap.RegisterEncoder("custom-format", func(config zapcore.EncoderConfig) (zapcore.Encoder, error) {
return &customFormatEncoder{
Encoder: zapcore.NewConsoleEncoder(config),
format: cfg.Format,
}, nil
})
if err != nil {
return nil, err
}
zCfg.Encoding = "custom-format"
}

if len(cfg.Output) != 0 {
zCfg.OutputPaths = cfg.Output
}
Expand Down
48 changes: 48 additions & 0 deletions custom_format_encoder.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package logger

import (
"fmt"
"strings"

"go.uber.org/zap/buffer"
"go.uber.org/zap/zapcore"
)

type customFormatEncoder struct {
format string
zapcore.Encoder
}

func (e *customFormatEncoder) Clone() zapcore.Encoder {
return &customFormatEncoder{Encoder: e.Encoder.Clone()}
}

func (e *customFormatEncoder) EncodeEntry(entry zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) {
str := e.format
replace := map[string]string{
"%level_name%": entry.Level.CapitalString(),
"%message%": entry.Message,
"%time%": fmt.Sprint(entry.Time.UnixMilli()),
"%stack%": entry.Stack,
"%caller_file%": entry.Caller.File,
"%caller_function%": entry.Caller.Function,
}

for s, r := range replace {
str = strings.ReplaceAll(str, s, r)
}

var contextValues = make([]string, 0, len(fields))
for _, v := range fields {
contextValues = append(contextValues, v.String)
}

str = strings.ReplaceAll(str, "%context%", strings.Join(contextValues, " "))

pool := buffer.NewPool()
buf := pool.Get()
buf.AppendString(str)
buf.AppendByte('\n')

return buf, nil
}