logging: Only colorize console output

This commit is contained in:
Matthew Holt 2020-04-08 14:37:37 -06:00
parent 5110643201
commit 6e4c688ea7
No known key found for this signature in database
GPG key ID: 2A349DD577D586A5

View file

@ -396,17 +396,6 @@ func (cl *CustomLog) provision(ctx Context, logging *Logging) error {
}
}
if cl.EncoderRaw != nil {
mod, err := ctx.LoadModule(cl, "EncoderRaw")
if err != nil {
return fmt.Errorf("loading log encoder module: %v", err)
}
cl.encoder = mod.(zapcore.Encoder)
}
if cl.encoder == nil {
cl.encoder = newDefaultProductionLogEncoder()
}
if cl.WriterRaw != nil {
mod, err := ctx.LoadModule(cl, "WriterRaw")
if err != nil {
@ -423,6 +412,23 @@ func (cl *CustomLog) provision(ctx Context, logging *Logging) error {
return fmt.Errorf("opening log writer using %#v: %v", cl.writerOpener, err)
}
if cl.EncoderRaw != nil {
mod, err := ctx.LoadModule(cl, "EncoderRaw")
if err != nil {
return fmt.Errorf("loading log encoder module: %v", err)
}
cl.encoder = mod.(zapcore.Encoder)
}
if cl.encoder == nil {
// only allow colorized output if this log is going to stdout or stderr
var colorize bool
switch cl.writerOpener.(type) {
case *StdoutWriter, *StderrWriter:
colorize = true
}
cl.encoder = newDefaultProductionLogEncoder(colorize)
}
cl.buildCore()
return nil
@ -650,7 +656,7 @@ func newDefaultProductionLog() (*defaultCustomLog, error) {
if err != nil {
return nil, err
}
cl.encoder = newDefaultProductionLogEncoder()
cl.encoder = newDefaultProductionLogEncoder(true)
cl.levelEnabler = zapcore.InfoLevel
cl.buildCore()
@ -661,14 +667,16 @@ func newDefaultProductionLog() (*defaultCustomLog, error) {
}, nil
}
func newDefaultProductionLogEncoder() zapcore.Encoder {
func newDefaultProductionLogEncoder(colorize bool) zapcore.Encoder {
encCfg := zap.NewProductionEncoderConfig()
if terminal.IsTerminal(int(os.Stdout.Fd())) {
// if interactive terminal, make output more human-readable by default
encCfg.EncodeTime = func(ts time.Time, encoder zapcore.PrimitiveArrayEncoder) {
encoder.AppendString(ts.UTC().Format("2006/01/02 15:04:05.000"))
}
if colorize {
encCfg.EncodeLevel = zapcore.CapitalColorLevelEncoder
}
return zapcore.NewConsoleEncoder(encCfg)
}
return zapcore.NewJSONEncoder(encCfg)