Categorygo.uber.org/zap
modulepackage
1.27.0
Repository: https://github.com/uber-go/zap.git
Documentation: pkg.go.dev

# README

:zap: zap

Blazing fast, structured, leveled logging in Go.

Zap logo

GoDoc Build Status Coverage Status

Installation

go get -u go.uber.org/zap

Note that zap only supports the two most recent minor versions of Go.

Quick Start

In contexts where performance is nice, but not critical, use the SugaredLogger. It's 4-10x faster than other structured logging packages and includes both structured and printf-style APIs.

logger, _ := zap.NewProduction()
defer logger.Sync() // flushes buffer, if any
sugar := logger.Sugar()
sugar.Infow("failed to fetch URL",
  // Structured context as loosely typed key-value pairs.
  "url", url,
  "attempt", 3,
  "backoff", time.Second,
)
sugar.Infof("Failed to fetch URL: %s", url)

When performance and type safety are critical, use the Logger. It's even faster than the SugaredLogger and allocates far less, but it only supports structured logging.

logger, _ := zap.NewProduction()
defer logger.Sync()
logger.Info("failed to fetch URL",
  // Structured context as strongly typed Field values.
  zap.String("url", url),
  zap.Int("attempt", 3),
  zap.Duration("backoff", time.Second),
)

See the documentation and FAQ for more details.

Performance

For applications that log in the hot path, reflection-based serialization and string formatting are prohibitively expensive — they're CPU-intensive and make many small allocations. Put differently, using encoding/json and fmt.Fprintf to log tons of interface{}s makes your application slow.

Zap takes a different approach. It includes a reflection-free, zero-allocation JSON encoder, and the base Logger strives to avoid serialization overhead and allocations wherever possible. By building the high-level SugaredLogger on that foundation, zap lets users choose when they need to count every allocation and when they'd prefer a more familiar, loosely typed API.

As measured by its own benchmarking suite, not only is zap more performant than comparable structured logging packages — it's also faster than the standard library. Like all benchmarks, take these with a grain of salt.1

Log a message and 10 fields:

PackageTimeTime % to zapObjects Allocated
:zap: zap656 ns/op+0%5 allocs/op
:zap: zap (sugared)935 ns/op+43%10 allocs/op
zerolog380 ns/op-42%1 allocs/op
go-kit2249 ns/op+243%57 allocs/op
slog (LogAttrs)2479 ns/op+278%40 allocs/op
slog2481 ns/op+278%42 allocs/op
apex/log9591 ns/op+1362%63 allocs/op
log1511393 ns/op+1637%75 allocs/op
logrus11654 ns/op+1677%79 allocs/op

Log a message with a logger that already has 10 fields of context:

PackageTimeTime % to zapObjects Allocated
:zap: zap67 ns/op+0%0 allocs/op
:zap: zap (sugared)84 ns/op+25%1 allocs/op
zerolog35 ns/op-48%0 allocs/op
slog193 ns/op+188%0 allocs/op
slog (LogAttrs)200 ns/op+199%0 allocs/op
go-kit2460 ns/op+3572%56 allocs/op
log159038 ns/op+13390%70 allocs/op
apex/log9068 ns/op+13434%53 allocs/op
logrus10521 ns/op+15603%68 allocs/op

Log a static string, without any context or printf-style templating:

PackageTimeTime % to zapObjects Allocated
:zap: zap63 ns/op+0%0 allocs/op
:zap: zap (sugared)81 ns/op+29%1 allocs/op
zerolog32 ns/op-49%0 allocs/op
standard library124 ns/op+97%1 allocs/op
slog196 ns/op+211%0 allocs/op
slog (LogAttrs)200 ns/op+217%0 allocs/op
go-kit213 ns/op+238%9 allocs/op
apex/log771 ns/op+1124%5 allocs/op
logrus1439 ns/op+2184%23 allocs/op
log152069 ns/op+3184%20 allocs/op

Development Status: Stable

All APIs are finalized, and no breaking changes will be made in the 1.x series of releases. Users of semver-aware dependency management systems should pin zap to ^1.

Contributing

We encourage and support an active, healthy community of contributors — including you! Details are in the contribution guide and the code of conduct. The zap maintainers keep an eye on issues and pull requests, but you can also report any negative conduct to [email protected]. That email list is a private, safe space; even the zap maintainers don't have access, so don't hesitate to hold us to a high standard.


Released under the MIT License.

1 In particular, keep in mind that we may be benchmarking against slightly older versions of other packages. Versions are pinned in the benchmarks/go.mod file.

# Packages

Package buffer provides a thin wrapper around a byte slice.
Package zapcore defines and implements the low-level interfaces upon which zap is built.
Package zapgrpc provides a logger that is compatible with grpclog.
Package zapio provides tools for interacting with IO streams through Zap.
Package zaptest provides a variety of helpers for testing log output.

# Functions

AddCaller configures the Logger to annotate each message with the filename, line number, and function name of zap's caller.
AddCallerSkip increases the number of callers skipped by caller annotation (as enabled by the AddCaller option).
AddStacktrace configures the Logger to record a stack trace for all messages at or above a given level.
Any takes a key and an arbitrary value and chooses the best way to represent them as a field, falling back to a reflection-based approach only if necessary.
Array constructs a field with the given key and ArrayMarshaler.
Binary constructs a field that carries an opaque binary blob.
Bool constructs a field that carries a bool.
Boolp constructs a field that carries a *bool.
Bools constructs a field that carries a slice of bools.
ByteString constructs a field that carries UTF-8 encoded text as a []byte.
ByteStrings constructs a field that carries a slice of []byte, each of which must be UTF-8 encoded text.
CombineWriteSyncers is a utility that combines multiple WriteSyncers into a single, locked WriteSyncer.
Complex128 constructs a field that carries a complex number.
Complex128p constructs a field that carries a *complex128.
Complex128s constructs a field that carries a slice of complex numbers.
Complex64 constructs a field that carries a complex number.
Complex64p constructs a field that carries a *complex64.
Complex64s constructs a field that carries a slice of complex numbers.
Development puts the logger in development mode, which makes DPanic-level logs panic instead of simply logging an error.
Dict constructs a field containing the provided key-value pairs.
Duration constructs a field with the given key and value.
Durationp constructs a field that carries a *time.Duration.
Durations constructs a field that carries a slice of time.Durations.
Error is shorthand for the common idiom NamedError("error", err).
ErrorOutput sets the destination for errors generated by the Logger.
Errors constructs a field that carries a slice of errors.
Fields adds fields to the Logger.
Float32 constructs a field that carries a float32.
Float32p constructs a field that carries a *float32.
Float32s constructs a field that carries a slice of floats.
Float64 constructs a field that carries a float64.
Float64p constructs a field that carries a *float64.
Float64s constructs a field that carries a slice of floats.
Hooks registers functions which will be called each time the Logger writes out an Entry.
IncreaseLevel increase the level of the logger.
Inline constructs a Field that is similar to Object, but it will add the elements of the provided ObjectMarshaler to the current namespace.
Int constructs a field with the given key and value.
Int16 constructs a field with the given key and value.
Int16p constructs a field that carries a *int16.
Int16s constructs a field that carries a slice of integers.
Int32 constructs a field with the given key and value.
Int32p constructs a field that carries a *int32.
Int32s constructs a field that carries a slice of integers.
Int64 constructs a field with the given key and value.
Int64p constructs a field that carries a *int64.
Int64s constructs a field that carries a slice of integers.
Int8 constructs a field with the given key and value.
Int8p constructs a field that carries a *int8.
Int8s constructs a field that carries a slice of integers.
Intp constructs a field that carries a *int.
Ints constructs a field that carries a slice of integers.
L returns the global Logger, which can be reconfigured with ReplaceGlobals.
LevelFlag uses the standard library's flag.Var to declare a global flag with the specified name, default, and usage guidance.
Must is a helper that wraps a call to a function returning (*Logger, error) and panics if the error is non-nil.
NamedError constructs a field that lazily stores err.Error() under the provided key.
Namespace creates a named, isolated scope within the logger's context.
New constructs a new Logger from the provided zapcore.Core and Options.
NewAtomicLevel creates an AtomicLevel with InfoLevel and above logging enabled.
NewAtomicLevelAt is a convenience function that creates an AtomicLevel and then calls SetLevel with the given level.
NewDevelopment builds a development Logger that writes DebugLevel and above logs to standard error in a human-friendly format.
NewDevelopmentConfig builds a reasonable default development logging configuration.
NewDevelopmentEncoderConfig returns an opinionated EncoderConfig for development environments.
NewExample builds a Logger that's designed for use in zap's testable examples.
NewNop returns a no-op Logger.
NewProduction builds a sensible production Logger that writes InfoLevel and above logs to standard error as JSON.
NewProductionConfig builds a reasonable default production logging configuration.
NewProductionEncoderConfig returns an opinionated EncoderConfig for production environments.
NewStdLog returns a *log.Logger which writes to the supplied zap Logger at InfoLevel.
NewStdLogAt returns *log.Logger which writes to supplied zap logger at required level.
Object constructs a field with the given key and ObjectMarshaler.
Objects constructs a field with the given key, holding a list of the provided objects that can be marshaled by Zap.
ObjectValues constructs a field with the given key, holding a list of the provided objects, where pointers to these objects can be marshaled by Zap.
OnFatal sets the action to take on fatal logs.
Open is a high-level wrapper that takes a variadic number of URLs, opens or creates each of the specified resources, and combines them into a locked WriteSyncer.
ParseAtomicLevel parses an AtomicLevel based on a lowercase or all-caps ASCII representation of the log level.
RedirectStdLog redirects output from the standard library's package-global logger to the supplied logger at InfoLevel.
RedirectStdLogAt redirects output from the standard library's package-global logger to the supplied logger at the specified level.
Reflect constructs a field with the given key and an arbitrary object.
RegisterEncoder registers an encoder constructor, which the Config struct can then reference.
RegisterSink registers a user-supplied factory for all sinks with a particular scheme.
ReplaceGlobals replaces the global Logger and SugaredLogger, and returns a function to restore the original values.
S returns the global SugaredLogger, which can be reconfigured with ReplaceGlobals.
Skip constructs a no-op field, which is often useful when handling invalid inputs in other Field constructors.
Stack constructs a field that stores a stacktrace of the current goroutine under provided key.
StackSkip constructs a field similarly to Stack, but also skips the given number of frames from the top of the stacktrace.
String constructs a field with the given key and value.
Stringer constructs a field with the given key and the output of the value's String method.
Stringers constructs a field with the given key, holding a list of the output provided by the value's String method Given an object that implements String on the value receiver, you can log a slice of those objects with Objects like so: type Request struct{ ..
Stringp constructs a field that carries a *string.
Strings constructs a field that carries a slice of strings.
Time constructs a Field with the given key and value.
Timep constructs a field that carries a *time.Time.
Times constructs a field that carries a slice of time.Times.
Uint constructs a field with the given key and value.
Uint16 constructs a field with the given key and value.
Uint16p constructs a field that carries a *uint16.
Uint16s constructs a field that carries a slice of unsigned integers.
Uint32 constructs a field with the given key and value.
Uint32p constructs a field that carries a *uint32.
Uint32s constructs a field that carries a slice of unsigned integers.
Uint64 constructs a field with the given key and value.
Uint64p constructs a field that carries a *uint64.
Uint64s constructs a field that carries a slice of unsigned integers.
Uint8 constructs a field with the given key and value.
Uint8p constructs a field that carries a *uint8.
Uint8s constructs a field that carries a slice of unsigned integers.
Uintp constructs a field that carries a *uint.
Uintptr constructs a field with the given key and value.
Uintptrp constructs a field that carries a *uintptr.
Uintptrs constructs a field that carries a slice of pointer addresses.
Uints constructs a field that carries a slice of unsigned integers.
WithCaller configures the Logger to annotate each message with the filename, line number, and function name of zap's caller, or not, depending on the value of enabled.
WithClock specifies the clock used by the logger to determine the current time for logged entries.
WithFatalHook sets a CheckWriteHook to run on fatal logs.
WithPanicHook sets a CheckWriteHook to run on Panic/DPanic logs.
WrapCore wraps or replaces the Logger's underlying zapcore.Core.

# Constants

DebugLevel logs are typically voluminous, and are usually disabled in production.
DPanicLevel logs are particularly important errors.
ErrorLevel logs are high-priority.
FatalLevel logs a message, then calls os.Exit(1).
InfoLevel is the default logging priority.
PanicLevel logs a message, then panics.
WarnLevel logs are more important than Info, but don't need individual human review.

# Structs

An AtomicLevel is an atomically changeable, dynamic logging level.
Config offers a declarative way to construct a logger.
A Logger provides fast, leveled, structured logging.
SamplingConfig sets a sampling strategy for the logger.
A SugaredLogger wraps the base Logger functionality in a slower, but less verbose, API.

# Interfaces

ObjectMarshalerPtr is a constraint that specifies that the given type implements zapcore.ObjectMarshaler on a pointer receiver.
An Option configures a Logger.
Sink defines the interface to write to and close logger destinations.

# Type aliases

Field is an alias for Field.
LevelEnablerFunc is a convenient way to implement zapcore.LevelEnabler with an anonymous function.