使用平板点分隔键新建文本编码器,以提高可读性和性能
Describe the problem you'd like to solve
Your feature request is related to a problem? Please describe.
Zap's current encoders (JSON, console) don't provide an easy-to-read text output for nested objects:
- JSONEncoder is structured but verbose and less operator-friendly for quick inspection in terminals.
- ConsoleEncoder is compact but does not handle nested objects in a way that makes them easy to grep or read.
- Alternatives like Kubernetes’ klog textlogger and Go's slog.TextHandler provide text output, but are either slower or less flexible.
Describe the solution you'd like
Introduce a new zapcore.Encoder implementation (e.g., TextEncoder) with the following features:
- Dot-flattened keys for nested objects
Example:
logger.Info("user created", zap.Any("user", User{
Name: "Alice",
Addr: Addr{City: "Bangalore", Zip: "560001"},
}))Current JSONEncoder output:
{"user": {"Name": "Alice", "Addr": {"City": "Bangalore", "Zip": "560001"}}}Proposed TextEncoder output:
"user.Name"="Alice" "user.Addr.City"="Bangalore" "user.Addr.Zip"="560001"This makes logs more human-readable and grep-friendly.
2. Performance improvements
Benchmarks show this encoder is faster than both k8s textlogger and slog.TextHandler, while competitive with zap’s json encoder.
3. Seamless zap integration
- Provided as a
zapcore.Encoderimplementation. - Configurable via
zapcore.NewTextEncoder(cfg)or zap configuration.
Describe alternatives you've considered
- Using JSONEncoder → too verbose and not grep-friendly.
- Using ConsoleEncoder → compact but nested structures are still hard to scan.
- Using Kubernetes’ klog textlogger / slog.TextHandler → slower and not integrated with zap.
Is this a breaking change?
No. This would be an additive change introducing a new encoder.
Existing users of JSONEncoder and ConsoleEncoder remain unaffected.
Additional context
- Prototype implementation: GitHub.com/sagarsuperuser/zap/tree/text-encoder
- Includes tests, benchmarks (https://GitHub.com/sagarsuperuser/zap/tree/text-encoder/benchmarks)
- Benchmarks :
Log a message and 10 fields
(https://GitHub.com/sagarsuperuser/zap/tree/text-encoder#log-a-message-and-10-fields)
| Package | Time (ns/op) | Time % vs Zap | Objects Allocated |
|---|---|---|---|
| ⚡ zap (json) | 656 | +0% | 5 allocs/op |
| ⚡ zap (text) | 852 | +30% | 5 allocs/op |
内容来源: uber-go/zap