uber-go / zap

Blazing fast, structured, leveled logging in Go.
https://pkg.go.dev/go.uber.org/zap
MIT License
22.04k stars 1.44k forks source link

Encoders should fall back to default Encode* implementations #537

Open dxvgef opened 6 years ago

dxvgef commented 6 years ago
package main

import (
    "time"

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

var Logger *zap.Logger

func main() {
    err := setLogger()
    if err != nil {
        println(err.Error())
        return
    }
    defer Logger.Sync()
    Logger.Debug("test")
}

func setLogger() (err error) {
    encodeConfig := zapcore.EncoderConfig{
        MessageKey: "message",
        LevelKey:   "level",
        TimeKey:    "time",
        NameKey:    "name",
        CallerKey:  "file",
        EncodeTime: timeEncoder,
    }
    config := zap.Config{
        Level:         zap.NewAtomicLevelAt(zapcore.DebugLevel),
        Development:   false,
        Encoding:      "json",
        EncoderConfig: encodeConfig,
        OutputPaths:   []string{"stderr"},
    }
    Logger, err = config.Build()
    return
}

func timeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
    enc.AppendString(t.Format("2006-01-02 15:04:05"))
}

It's normal to change "Encoding" to "console"

billf commented 6 years ago

zapcore.EncoderConfig requires an encoder for the keys you've specified. encodeConfig.LevelKey is set but encodeConfig.EncodeLevel is not.

https://godoc.org/go.uber.org/zap/zapcore#EncoderConfig

You can use the system defaults for the rest of the encoders:

        EncodeLevel:    zapcore.LowercaseLevelEncoder,
        EncodeDuration: zapcore.SecondsDurationEncoder,
        EncodeCaller:   zapcore.ShortCallerEncoder,

It's possibly a bug that Config.Build does not error here.

akshayjshah commented 6 years ago

I went back and forth on this, and at the time settled on forcing users of this API to be explicit about the behavior they'd prefer.

We could make config.Build error here, or we could make zapcore.NewJSONEncoder and zapcore.NewConsoleEncoder automatically fall back to the default encoders.