Zap Logger: Sugared vs Unsugared
In this tutorial, you'll learn about Zap Logger: Sugared vs Unsugared. We cover key concepts, practical examples, and best practices.
Zap logger sugar -- Use zap.SugaredLogger for readable printf-style logging and zap.Logger for high-performance structured logging.
The Problem
Zap has two APIs: the fast, structured zap.Logger and the more flexible zap.SugaredLogger. Using the wrong one leads to verbose code or performance regressions.
Wrong
logger, _ := zap.NewProduction()
logger.Info("user login",
zap.String("username", name),
zap.Int("attempts", count))
Output:
// Explicit fields every time. Verbose for simple messages.
Right
logger, _ := zap.NewProduction()
sugar := logger.Sugar()
sugar.Infow("user login",
"username", name,
"attempts", count)
Output:
// Infow uses key-value pairs. Shorter and readable.
Prevention
- Use SugaredLogger for application code and quick prototyping
- Use zap.Logger in hot paths (more efficient)
- Sugar adds ~60% overhead vs zap.Logger
- Use Desugar() to get Logger from Sugar
- Use Sugar() to get SugaredLogger from Logger
Common Mistakes with log zap sugar
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro