or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

configuration.mdfields.mdindex.mdintegrations.mdlogger.mdtesting.mdzapcore.md
tile.json

index.mddocs/

Zap - High-Performance Structured Logging for Go

Zap 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.

Package Information

  • Package Name: go.uber.org/zap
  • Package Type: Go module
  • Language: Go
  • Installation: go get -u go.uber.org/zap
  • Version: 1.27.1

Core Imports

import (
    "go.uber.org/zap"
    "go.uber.org/zap/zapcore"
)

Basic Usage

Quick Start with Presets

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"),
)

SugaredLogger for Convenience

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,
)

Architecture

Zap is built on a layered architecture:

  • High-level API (zap package): Logger and SugaredLogger provide the primary logging interfaces
  • Core layer (zapcore package): Pluggable interfaces for encoders, writers, and cores enable extensibility
  • Field system: Strongly-typed fields avoid reflection and allocations
  • Configuration: Both programmatic (New, Options) and declarative (Config) approaches supported

Capabilities

Logger Types

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() error
type 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() *Logger

Logger and SugaredLogger Details

Logger Creation

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) *Logger

Logger Creation and Configuration

Strongly-Typed Fields

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) Field

Complete Field Constructor Reference

Configuration and Options

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) Option

Configuration and Options Details

Core Interfaces and Extensibility

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) Encoder

zapcore Package Details

Testing Support

Utilities 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) *ObservedLogs

Testing Utilities

Integration Packages

Integrations 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) *Handler

Integration Packages

Log Levels

const (
    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)
)

Global Logger Functions

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.

Standard Library Integration

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.