zap

package module
v0.7.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 2, 2025 License: MIT Imports: 6 Imported by: 1

README

zap

Go Reference codecov

Bidirectional adapter between Uber's zap and darvaza.org/slog.

This package provides two-way integration:

  • zap → slog: Use a zap logger as the backend for slog.Logger interface.
  • slog → zap: Implement zapcore.Core to create zap loggers backed by any slog implementation.

Installation

go get darvaza.org/slog/handlers/zap

Quick Start

Using zap as slog backend (zap → slog)
import (
    "go.uber.org/zap"
    "go.uber.org/zap/zapcore"
    slogzap "darvaza.org/slog/handlers/zap"
)

// Create a zap config
zapConfig := slogzap.NewDefaultConfig() // or zap.NewProductionConfig()

// Create slog adapter
slogLogger, err := slogzap.New(zapConfig)
if err != nil {
    panic(err)
}

// Or with zap options (e.g., for testing with a custom core)
slogLogger, err := slogzap.New(zapConfig,
    zap.WrapCore(func(core zapcore.Core) zapcore.Core {
        // Replace or wrap the core as needed
        return core
    }),
)
if err != nil {
    panic(err)
}

// Use with slog interface
slogLogger.Info().
    WithField("latency_ms", 42).
    WithField("status", 200).
    WithField("method", "GET").
    Print("Request completed")
Using slog as zap backend (slog → zap)
import (
    "darvaza.org/slog"
    "darvaza.org/slog/handlers/filter"
    slogzap "darvaza.org/slog/handlers/zap"
    "go.uber.org/zap"
)

// Start with any slog implementation
baseLogger := getSlogLogger() // your existing slog logger
filtered := filter.New(baseLogger, filter.MinLevel(slog.Info))

// Create a zap logger backed by slog
zapLogger := slogzap.NewZapLogger(filtered)

// Use with zap interface
zapLogger.Info("Request completed",
    zap.Int("latency_ms", 42),
    zap.Int("status", 200),
    zap.String("method", "GET"),
)

// Or create with custom options
core := slogzap.NewCore(filtered, zap.InfoLevel)
zapLogger = zap.New(core,
    zap.AddCaller(),
    zap.AddStacktrace(zap.ErrorLevel),
)

Breaking Changes

v0.7.0: The New() function now returns (slog.Logger, error) instead of just slog.Logger to properly handle configuration build errors. Additionally, it now accepts variadic zap.Option parameters for customizing the logger.

Features

  • Bidirectional Integration: Convert between zap and slog in both directions.
  • High Performance: Leverages zap's zero-allocation design.
  • Full Compatibility: Supports all features of both logging systems.
  • Flexible Architecture: Use zap's API with any slog backend, or vice versa.
  • Thread-Safe: Immutable logger instances with safe field management.
  • Production Ready: Battle-tested with comprehensive test coverage.

Use Cases

When to use zap → slog
  • You have existing zap infrastructure but want to use slog's interface
  • You need to integrate with libraries that expect slog.Logger
  • You want to apply slog middleware (filters, transformers) to zap output
When to use slog → zap
  • You have an slog backend but need to use libraries that require zap
  • You want zap's rich API while writing to a custom slog implementation
  • You're migrating between logging systems and need to support both APIs

Level Mapping

slog Level zap Level Behaviour
Debug Debug Standard mapping
Info Info Standard mapping
Warn Warn Standard mapping
Error Error Standard mapping
Fatal Fatal Calls os.Exit(1)
Panic Panic/DPanic Calls panic()

Note: DPanic (Development Panic) maps to slog.Panic and triggers panic() behaviour.

Performance Tips

  • Use zap.NewProductionConfig() for best performance.
  • Avoid console encoders in production.
  • Pre-compute expensive field values.
  • Consider using zap.Logger directly for hot paths.

Documentation

Documentation

Overview

Package zap provides a slog.Logger adaptor using a go.uber.org/zap Logger as backend

Index

Constants

View Source
const (
	// DefaultLogLevel is the default log level for new loggers
	DefaultLogLevel = slog.Info
)

Variables

This section is empty.

Functions

func New

func New(cfg *zap.Config, zapOptions ...zap.Option) (slog.Logger, error)

New creates a slog.Logger adaptor using a zap as backend. If none was passed it will create an opinionated new one.

func NewCore added in v0.7.0

func NewCore(logger slog.Logger, level zapcore.LevelEnabler) zapcore.Core

NewCore creates a zapcore.Core that writes to the provided slog.Logger

func NewDefaultConfig added in v0.3.7

func NewDefaultConfig() *zap.Config

NewDefaultConfig creates a new zap.Config logging to the console.

func NewZapLogger added in v0.7.0

func NewZapLogger(logger slog.Logger, opts ...zap.Option) *zap.Logger

NewZapLogger creates a *zap.Logger that writes to the provided slog.Logger

Types

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger is an adaptor using go.uber.org/zap as slog.Logger

func NewNoop

func NewNoop() *Logger

NewNoop returns a no-op Logger. It never writes out logs or internal errors

func (*Logger) Debug

func (zpl *Logger) Debug() slog.Logger

Debug returns a new logger set to add entries as level Debug

func (*Logger) Enabled

func (zpl *Logger) Enabled() bool

Enabled tells this logger is enabled

func (*Logger) Error

func (zpl *Logger) Error() slog.Logger

Error returns a new logger set to add entries as level Error

func (*Logger) Fatal

func (zpl *Logger) Fatal() slog.Logger

Fatal returns a new logger set to add entries as level Fatal

func (*Logger) Info

func (zpl *Logger) Info() slog.Logger

Info returns a new logger set to add entries as level Info

func (*Logger) Level added in v0.7.1

func (zpl *Logger) Level() slog.LogLevel

Level returns the current log level. Exposed for testing only.

func (*Logger) NewWithCallback

func (zpl *Logger) NewWithCallback(fn func(lv zapcore.Entry) error) *Logger

NewWithCallback creates a new zap logger using a callback to modify it.

func (*Logger) Panic

func (zpl *Logger) Panic() slog.Logger

Panic returns a new logger set to add entries as level Panic

func (*Logger) Print

func (zpl *Logger) Print(args ...any)

Print adds a log entry with arguments handled in the manner of fmt.Print

func (*Logger) Printf

func (zpl *Logger) Printf(format string, args ...any)

Printf adds a log entry with arguments handled in the manner of fmt.Printf

func (*Logger) Println

func (zpl *Logger) Println(args ...any)

Println adds a log entry with arguments handled in the manner of fmt.Println

func (*Logger) Unwrap added in v0.3.7

func (zpl *Logger) Unwrap() (*zap.Logger, *zap.Config)

Unwrap returns the underlying zap logger

func (*Logger) Warn

func (zpl *Logger) Warn() slog.Logger

Warn returns a new logger set to add entries as level Warn

func (*Logger) WithEnabled

func (zpl *Logger) WithEnabled() (slog.Logger, bool)

WithEnabled passes the logger and if it's enabled

func (*Logger) WithField

func (zpl *Logger) WithField(label string, value any) slog.Logger

WithField returns a new logger with a field attached

func (*Logger) WithFields

func (zpl *Logger) WithFields(fields map[string]any) slog.Logger

WithFields returns a new logger with a set of fields attached

func (*Logger) WithLevel

func (zpl *Logger) WithLevel(level slog.LogLevel) slog.Logger

WithLevel returns a new logger set to add entries to the specified level

func (*Logger) WithStack

func (zpl *Logger) WithStack(skip int) slog.Logger

WithStack attaches a call stack to a new logger

type SlogCore added in v0.7.0

type SlogCore struct {
	// contains filtered or unexported fields
}

SlogCore implements zapcore.Core using slog.Logger as backend

func (*SlogCore) Check added in v0.7.0

func (c *SlogCore) Check(entry zapcore.Entry, checked *zapcore.CheckedEntry) *zapcore.CheckedEntry

Check determines whether the logger should log at the given level

func (*SlogCore) Enabled added in v0.7.0

func (c *SlogCore) Enabled(level zapcore.Level) bool

Enabled returns whether the given level is enabled

func (*SlogCore) Sync added in v0.7.0

func (*SlogCore) Sync() error

Sync flushes any buffered log entries

func (*SlogCore) With added in v0.7.0

func (c *SlogCore) With(fields []zapcore.Field) zapcore.Core

With returns a new Core with additional fields

func (*SlogCore) Write added in v0.7.0

func (c *SlogCore) Write(entry zapcore.Entry, fields []zapcore.Field) error

Write serializes the Entry and any Fields to the slog backend

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL