stolostron / multicluster-global-hub

the main repository for the multicluster global hub
Apache License 2.0
21 stars 32 forks source link

Format the log #1178

Open yanmxa opened 1 month ago

yanmxa commented 1 month ago

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:

Library Log Format Log Level Configuration Code Location Time Formatting Dynamic Level Support GitHub Stars Notes
glog Text-based Via -v flag for verbosity levels Yes, with log.V() calls Default format (RFC3339) No 3.4k Simple interface, widely used in Go​GitHub​GitHub.
zap JSON or text Configurable at initialization with log levels Yes, includes caller information Customizable format Yes 19.2k High performance, structured logging​GitHub.
zapr JSON or text Follows zap’s configuration via logr Yes, includes caller information Customizable format Yes 127 Adapter for zap, integrates with logr​GitHub​GitHub.
logr Varies by backend Controlled via context or runtime configuration Yes, via WithValues Format varies by backend Yes 836 Flexible, interface for structured logging​GitHub.
klog Text-based Set via --v flag for verbosity levels Yes, provides file and line details Default format (RFC3339) No 526 Designed for Kubernetes, simpler format​GitHub.
yanmxa commented 1 month ago

zap Vs zapr ?

yanmxa commented 1 month ago
  1. Using the zapr, which can be invoked by the interface logr easily. The only concern is it only supports DEBUG, INFO, and ERROR
  2. Using the zap is straightforward! However, we need to change the way we log structured information. For example, log the key value with zap.String("username", "john_doe")
yanmxa commented 1 month ago

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)