Blazing fast, structured, leveled logging in Go
npx @tessl/cli install tessl/golang-go-uber-org--zap@1.27.0Zap is a blazing fast, structured, leveled logging library for Go. It provides both a strongly-typed Logger for performance-critical hot paths and a more flexible SugaredLogger for convenience. Zap achieves 4-10x faster performance than other structured logging packages through zero-allocation JSON encoding and careful allocation management.
go get -u go.uber.org/zapimport (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)import "go.uber.org/zap"
// Production logger (JSON, InfoLevel+, stderr)
logger, _ := zap.NewProduction()
defer logger.Sync()
logger.Info("failed to fetch URL",
zap.String("url", "http://example.com"),
zap.Int("attempt", 3),
zap.Duration("backoff", time.Second),
)
// Development logger (console, DebugLevel+, stderr)
devLogger, _ := zap.NewDevelopment()
devLogger.Debug("debugging information",
zap.String("module", "authentication"),
)sugar := logger.Sugar()
defer sugar.Sync()
// Printf-style
sugar.Infof("Failed to fetch URL: %s", url)
// Structured key-value pairs
sugar.Infow("failed to fetch URL",
"url", url,
"attempt", 3,
"backoff", time.Second,
)Zap is built on a layered architecture:
Zap provides two logger types optimized for different use cases.
type Logger struct { /* ... */ }
func (log *Logger) Debug(msg string, fields ...Field)
func (log *Logger) Info(msg string, fields ...Field)
func (log *Logger) Warn(msg string, fields ...Field)
func (log *Logger) Error(msg string, fields ...Field)
func (log *Logger) Panic(msg string, fields ...Field)
func (log *Logger) Fatal(msg string, fields ...Field)
func (log *Logger) With(fields ...Field) *Logger
func (log *Logger) Sugar() *SugaredLogger
func (log *Logger) Sync() errortype SugaredLogger struct { /* ... */ }
func (s *SugaredLogger) Debugw(msg string, keysAndValues ...interface{})
func (s *SugaredLogger) Infow(msg string, keysAndValues ...interface{})
func (s *SugaredLogger) Warnw(msg string, keysAndValues ...interface{})
func (s *SugaredLogger) Errorw(msg string, keysAndValues ...interface{})
func (s *SugaredLogger) Debugf(template string, args ...interface{})
func (s *SugaredLogger) Infof(template string, args ...interface{})
func (s *SugaredLogger) Desugar() *LoggerLogger and SugaredLogger Details
Multiple ways to create loggers for different scenarios.
// Preset constructors
func NewProduction(options ...Option) (*Logger, error)
func NewDevelopment(options ...Option) (*Logger, error)
func NewExample(options ...Option) *Logger
func NewNop() *Logger
// Custom logger from core
func New(core zapcore.Core, options ...Option) *LoggerLogger Creation and Configuration
Efficient, type-safe field constructors for structured logging.
// Primitive types
func String(key string, val string) Field
func Int(key string, val int) Field
func Int64(key string, val int64) Field
func Bool(key string, val bool) Field
func Float64(key string, val float64) Field
func Time(key string, val time.Time) Field
func Duration(key string, val time.Duration) Field
// Complex types
func Error(err error) Field
func Any(key string, value interface{}) Field
func Object(key string, val zapcore.ObjectMarshaler) Field
// Arrays
func Strings(key string, vals []string) Field
func Ints(key string, nums []int) FieldComplete Field Constructor Reference
Declarative configuration and programmatic options for customizing logger behavior.
type Config struct {
Level AtomicLevel
Development bool
DisableCaller bool
DisableStacktrace bool
Sampling *SamplingConfig
Encoding string
EncoderConfig zapcore.EncoderConfig
OutputPaths []string
ErrorOutputPaths []string
InitialFields map[string]interface{}
}
func (cfg Config) Build(opts ...Option) (*Logger, error)
// Option functions
func AddCaller() Option
func AddStacktrace(lvl zapcore.LevelEnabler) Option
func Development() Option
func Fields(fs ...Field) Option
func WrapCore(f func(zapcore.Core) zapcore.Core) OptionConfiguration and Options Details
Low-level interfaces for extending zap with custom encoders, sinks, and cores.
type Core interface {
Enabled(Level) bool
With([]Field) Core
Check(Entry, *CheckedEntry) *CheckedEntry
Write(Entry, []Field) error
Sync() error
}
type Encoder interface {
ObjectEncoder
Clone() Encoder
EncodeEntry(Entry, []Field) (*buffer.Buffer, error)
}
type WriteSyncer interface {
Write([]byte) (int, error)
Sync() error
}
func NewCore(enc Encoder, ws WriteSyncer, enab LevelEnabler) Core
func NewJSONEncoder(cfg EncoderConfig) Encoder
func NewConsoleEncoder(cfg EncoderConfig) EncoderUtilities for testing code that uses zap loggers.
// zaptest package
func NewLogger(t TestingT, opts ...LoggerOption) *zap.Logger
// zaptest/observer package
func New(enab zapcore.LevelEnabler) (*zap.Logger, *ObservedLogs)
type ObservedLogs struct { /* ... */ }
func (o *ObservedLogs) All() []LoggedEntry
func (o *ObservedLogs) FilterMessage(msg string) *ObservedLogsIntegrations with gRPC, IO, and experimental features.
// zapgrpc - gRPC logger adapter
func NewLogger(l *zap.Logger, options ...Option) *Logger
// zapio - io.Writer wrapper
type Writer struct {
Log *zap.Logger
Level zapcore.Level
}
// exp/zapslog - slog.Handler implementation (Go 1.21+)
func NewHandler(core zapcore.Core, opts ...HandlerOption) *Handlerconst (
DebugLevel = zapcore.DebugLevel // -1: Debug logs (verbose)
InfoLevel = zapcore.InfoLevel // 0: Info logs (default)
WarnLevel = zapcore.WarnLevel // 1: Warning logs
ErrorLevel = zapcore.ErrorLevel // 2: Error logs
DPanicLevel = zapcore.DPanicLevel // 3: Panic in development
PanicLevel = zapcore.PanicLevel // 4: Panic always
FatalLevel = zapcore.FatalLevel // 5: Fatal (exits)
)func L() *Logger
func S() *SugaredLogger
func ReplaceGlobals(logger *Logger) func()Global logger functions provide access to package-level loggers. By default, these return a no-op logger. Use ReplaceGlobals to set a custom global logger.
func NewStdLog(l *Logger) *log.Logger
func NewStdLogAt(l *Logger, level zapcore.Level) (*log.Logger, error)
func RedirectStdLog(l *Logger) func()
func RedirectStdLogAt(l *Logger, level zapcore.Level) (func(), error)These functions enable integration with Go's standard log package, either by creating stdlib-compatible loggers backed by zap, or by redirecting the global stdlib logger to zap.