测试从自定义配置构建的Logger的zap日志记录

时间:2018-10-10 07:06:50

标签: go logging

我有一个从自定义Config(即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()
}

2 个答案:

答案 0 :(得分:3)

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)
        }
    }
}

答案 1 :(得分:1)

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")
    }
}