zap
Structured, leveled logging in Go with zero-allocation fields and strongly typed encoders.
Official Documentation ↗v1.27. Check the official docs for the latest API surface.Installation
go get go.uber.org/zapMethods
No methods match this filter.
Structured, leveled logging in Go with zero-allocation fields and strongly typed encoders.
Overview
zap is a leveled, structured logger engineered for throughput: typed field constructors avoid interface boxing, and the encoder writes JSON or console output directly. Production and development presets cover common setups, and every part is configurable through cores and options.
The sugared facade keeps printf ergonomics for code that is not hot, global accessors integrate libraries, and With creates scoped loggers that carry context fields across every subsequent call.
Core Methods
The most frequently used entry points, with signatures and runnable examples:
zap.NewProduction / NewDevelopment— Prebuilt configs: JSON with timestamps and stacktraces for prod, console with colors for dev.logger.Info— Emits an event with typed fields; field constructors avoid allocations and boxing.Sugared logger— Loosely typed facade accepting key-value pairs and printf templates at a small performance cost.zap.L() / zap.ReplaceGlobals— Global access for libraries, plus With-derived loggers that carry bound context cheaply.
Usage Notes
- Prefer structured fields over message interpolation; they stay queryable downstream.
- Create request-scoped loggers with With instead of threading trace IDs through every call.
- Wrap Sync errors for terminal outputs rather than failing startup over an expected EINVAL.
Common Pitfalls
- Calling Sugar() per log statement reintroduces allocations and defeats the purpose.
- zap.Error(err) records the error with its stack; fmt.Errorf-wrapped context belongs in fields, not the message.
- A logger built with NewNopCore swallows everything; check wiring when logs go missing.
FAQ
- Why does Sync return an error on stdout?
- Sync flushes buffers, and the Linux implementation returns EINVAL for terminals and some stdout setups. Ignore or log the Sync error for console destinations; it matters for file and socket-based writers.
- Should I use the core or sugared API?
- The core API with typed fields is allocation-free and right for hot paths. The sugared API trades a little performance for printf and loose key-value ergonomics, convenient at boundaries and prototypes. Both share configuration.
- How do I add a trace ID to every log line?
- Derive a child logger once per request with logger.With(zap.String("trace_id", id)) and pass it down, or use zap fields in middleware. Binding once is cheaper than passing the field at every call site.
Report a problem with this API docOpens a pre-filled issue on GitHub.