Open yanmxa opened 1 month ago
zapcore.Filed
to structure the key/value entries
logger.Info("Info log", zap.String("username", "john_doe"))
2024-10-24T10:12:48.259+0800 DEBUG log-zap/main.go:38 Debug message with custom encoder - debug level
2024-10-24T10:12:48.259+0800 INFO log-zap/main.go:39 Info message - debug level {"username": "john_doe"}
2024-10-24T10:12:48.259+0800 WARN log-zap/main.go:40 Warning message - debug level
main.main
/Users/yanmeng/Workspace/redhat/hub-of-hubs/samples/log-zap/main.go:40
runtime.main
/Users/yanmeng/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.22.5.darwin-arm64/src/runtime/proc.go:271
2024-10-24T10:12:48.259+0800 INFO log-zap/main.go:44 Info message - info level
2024-10-24T10:12:48.259+0800 WARN log-zap/main.go:45 Warning message - info level
main.main
/Users/yanmeng/Workspace/redhat/hub-of-hubs/samples/log-zap/main.go:45
runtime.main
/Users/yanmeng/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.22.5.darwin-arm64/src/runtime/proc.go:271
log.V(0).Info("info", "key", "val")
The cons
V(0)
typically corresponds to INFO
, and V(1)
to DEBUG
, levels beyond V(1) may not behave as expected, as zap doesn't directly map them.DEBUG
, INFO
, and ERROR
levels are sufficient and works well for typical use cases.zc.Level.SetLevel(-2)
...
log.V(2).Info("-2heloo2", "ni", "hao")
...
2024-10-23T21:00:22.363+0800 LEVEL(-2) log-zapr/main.go:83 -2heloo2 {"ni": "hao"}
2024-10-24T10:18:10.630+0800 LEVEL(-2) log-zapr/main.go:81 V2 message {"ni": "hao"}
2024-10-24T10:18:10.630+0800 DEBUG log-zapr/main.go:82 V1 message(Debug) {"ni": "hao"}
2024-10-24T10:18:10.630+0800 INFO log-zapr/main.go:83 Info message {"key": "val"}
DEBUG
, INFO
, and ERROR
zap.String("username", "john_doe")
The only concern with using the Zap is the structured API. To avoid using its strict print mode, we can use its subpackage, sugar!
Reference: https://github.com/uber-go/zap/issues/138
Sugar wraps the Logger to provide a more ergonomic, but slightly slower, API. Sugaring a Logger is quite inexpensive, so it's reasonable for a single application to use both Loggers and SugaredLoggers, converting between them on the boundaries of performance-sensitive code
logger, _ := zap.NewProduction()
defer logger.Sync() // flushes buffer, if any
sugar := logger.Sugar()
sugar.Infow("failed to fetch URL",
// Structured context as loosely typed key-value pairs.
"url", url,
"attempt", 3,
"backoff", time.Second,
)
sugar.Infof("Failed to fetch URL: %s", url)
Here's a comprehensive comparison of the specified logging libraries based on various features, including log format, log level configuration, dynamic change log level, log code location, and time formatting: