7

我有一个从自定义配置(即config.Build())生成的 Zap 记录器。我想通过调用来测试记录器,例如,logger.Info()在测试方法中并断言结果以查看它是否符合配置集。我怎样才能做到这一点?

代码示例:

func GetLogger() *zap.Logger{
 config := &zap.Config{
  Encoding: "json",
  Level: zap.NewAtomicLevelAt(zapcore.InfoLevel),
  OutputPaths: []string{"stdout"},
  ErrorOutputPaths: []string{"stdout"},
  EncoderConfig: zapcore.EncoderConfig{
   MessageKey: "@m",
   LevelKey:    "@l",
   EncodeLevel: zapcore.CapitalLevelEncoder,
   TimeKey:    "@t",
   EncodeTime: zapcore.EpochMillisTimeEncoder,
   CallerKey:     "@c",
   EncodeCaller:  zapcore.ShortCallerEncoder,
   StacktraceKey: "@x",
  },
 }
 return config.Build()
}
4

2 回答 2

12

zap 有一个zaptest/observer用于单元测试的特殊模块:

package test

import (
    "testing"

    "go.uber.org/zap"
    "go.uber.org/zap/zaptest/observer"
)

func setupLogsCapture() (*zap.Logger, *observer.ObservedLogs) {
    core, logs := observer.New(zap.InfoLevel)
    return zap.New(core), logs
}

func Test(t *testing.T) {
    logger, logs := setupLogsCapture()
    
    logger.Warn("This is the warning")
    
    if logs.Len() != 1 {
        t.Errorf("No logs")
    } else {
        entry := logs.All()[0]
        if entry.Level != zap.WarnLevel || entry.Message != "This is the warning" {
            t.Errorf("Invalid log entry %v", entry)
        }
    }
}
于 2020-06-22T21:42:52.060 回答
11

Zap 有一个sinks的概念,即日志消息的目的地。为了测试,实现一个只记住消息的接收器(例如在 bytes.Buffer 中):

package main

import (
    "bytes"
    "net/url"
    "strings"
    "testing"
    "time"

    "go.uber.org/zap"
)

// MemorySink implements zap.Sink by writing all messages to a buffer.
type MemorySink struct {
    *bytes.Buffer
}

// Implement Close and Sync as no-ops to satisfy the interface. The Write 
// method is provided by the embedded buffer.

func (s *MemorySink) Close() error { return nil }
func (s *MemorySink) Sync() error  { return nil }


func TestLogger(t *testing.T) {
    // Create a sink instance, and register it with zap for the "memory" 
    // protocol.
    sink := &MemorySink{new(bytes.Buffer)}
    zap.RegisterSink("memory", func(*url.URL) (zap.Sink, error) {
        return sink, nil
    })

    conf := zap.NewProductionConfig() // TODO: replace with real config

    // Redirect all messages to the MemorySink.    
    conf.OutputPaths = []string{"memory://"}

    l, err := conf.Build()
    if err != nil {
        t.Fatal(err)
    }

    l.Info("failed to fetch URL",
        zap.String("url", "http://example.com"),
        zap.Int("attempt", 3),
        zap.Duration("backoff", time.Second),
    )

    // Assert sink contents

    output := sink.String()
    t.Logf("output = %s", output)

    if !strings.Contains(output, `"url":"http://example.com"`) {
        t.Error("output missing: url=http://example.com")
    }
}
于 2018-10-10T10:18:02.800 回答