如何测试从自定义配置构建的 zap Logger 的日志记录?
How to test logging of a zap Logger built from custom Config?
我有一个从自定义配置生成的 Zap 记录器(即 config.Build()
)。我想通过在测试方法中调用 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()
}
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")
}
}
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)
}
}
}
我有一个从自定义配置生成的 Zap 记录器(即 config.Build()
)。我想通过在测试方法中调用 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()
}
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")
}
}
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)
}
}
}