Categorygithub.com/uber-go/zap
modulepackage
0.1.0-beta.1
Repository: https://github.com/uber-go/zap.git
Documentation: pkg.go.dev

# README

:zap: zap GoDoc Build Status Coverage Status

Blazing fast, structured, leveled logging in Go.

Installation

go get -u github.com/uber-go/zap

Structure

Zap takes an opinionated stance on logging and doesn't provide any printf-style helpers. Rather than logger.Printf("Failed to fetch URL %s (attempt %v), sleeping %s before retry.", url, tryNum, sleepFor), zap encourages the more structured

logger.Info("Failed to fetch URL.",
  zap.String("url", url),
  zap.Int("attempt", tryNum),
  zap.Duration("backoff", sleepFor),
)

This a bit more verbose, but it enables powerful ad-hoc analysis, flexible dashboarding, and accurate message bucketing. In short, it helps you get the most out of tools like ELK, Splunk, and Sentry. All log messages are JSON-serialized, though PRs to support other formats are welcome.

For compatibility with the standard library and bark, zap provides the zwrap.Standardize and zbark.Barkify wrappers. Both are slower than the core zap logger, but faster than the libraries they replace.

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 it offers a variety of type-safe ways to add structured context to your log messages. It strives to avoid serialization overhead and allocations wherever possible, so collecting rich debug logs doesn't impact normal operations.

As measured by its own benchmarking suite, not only is zap more performant than comparable structured logging libraries — 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:

LibraryTimeBytes AllocatedObjects Allocated
:zap: zap1279 ns/op705 B/op2 allocs/op
logrus10369 ns/op5275 B/op78 allocs/op
go-kit6969 ns/op3204 B/op70 allocs/op
log1522246 ns/op4783 B/op91 allocs/op
apex/log16379 ns/op3608 B/op63 allocs/op

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

LibraryTimeBytes AllocatedObjects Allocated
:zap: zap231 ns/op0 B/op0 allocs/op
logrus8532 ns/op3438 B/op61 allocs/op
go-kit6874 ns/op2486 B/op48 allocs/op
log1520462 ns/op4118 B/op70 allocs/op
apex/log13886 ns/op2384 B/op48 allocs/op

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

LibraryTimeBytes AllocatedObjects Allocated
:zap: zap222 ns/op0 B/op0 allocs/op
standard library565 ns/op32 B/op2 allocs/op
logrus3085 ns/op1336 B/op26 allocs/op
go-kit1061 ns/op624 B/op13 allocs/op
log155462 ns/op1351 B/op23 allocs/op
apex/log3009 ns/op584 B/op11 allocs/op

Development Status: Beta

Ready for adventurous users, but we're planning several breaking changes before releasing version 1.0. This project tracks our progress toward a stable release.


Released under the [MIT License](LICENSE.txt).

1 In particular, keep in mind that we may be benchmarking against slightly older versions of other libraries. Versions are pinned in zap's glide.lock file.

# Packages

Package spy provides an implementation of zap.Logger that helps test logging wrappers.
Package spywrite provides various I/O implementations with known errors.
Package testutils provides some simple testing helpers (most of which aren't specifically logging-related).
Package zbark provides a wrapper to make zap.Loggers compatible with the bark.Logger interface and a wrapper to make bark.Loggers compatible with zap.Logger interface.
Package zwrap provides a variety of wrappers for the core zap logger.

# Functions

AddCaller configures the Logger to annotate each message with the filename and line number of zap's caller.
AddStacks configures the Logger to record a stack trace for all messages at or above a given level.
AddSync converts an io.Writer to a WriteSyncer.
Base64 constructs a field that encodes the given value as a padded base64 string.
Bool constructs a Field with the given key and value.
Development puts the logger in development mode, which alters the behavior of the DPanic method.
Duration constructs a Field with the given key and value.
DynamicLevel creates an atomically changeable dynamic logging level.
EpochFormatter uses the Time field (floating-point seconds since epoch) to encode the entry time under the provided key.
Error constructs a Field that lazily stores err.Error() under the key "error".
ErrorOutput sets the destination for errors generated by the logger.
Fields sets the initial fields for the logger.
Float64 constructs a Field with the given key and value.
Int constructs a Field with the given key and value.
Int64 constructs a Field with the given key and value.
LevelFlag defines a Level flag with specified name, default value and usage string.
LevelString encodes the entry's level under the provided key.
MakeMeta returns a new meta struct with sensible defaults: logging at InfoLevel, development mode off, and writing to standard error and standard out.
Marshaler constructs a field with the given key and zap.LogMarshaler.
MessageKey encodes log messages under the provided key.
MultiWriteSyncer creates a WriteSyncer that duplicates its writes and sync calls, similarly to to io.MultiWriter.
Nest takes a key and a variadic number of Fields and creates a nested namespace.
New constructs a logger that uses the provided encoder.
NewCheckedMessage constructs a CheckedMessage.
NewJSONEncoder creates a fast, low-allocation JSON encoder.
NewTextEncoder creates a line-oriented text encoder whose output is optimized for human, rather than machine, consumption.
NoTime drops the entry time altogether.
NullEncoder returns the fast, no-allocation encoder.
Object constructs a field with the given key and an arbitrary object.
Output sets the destination for the logger's output.
RFC3339Formatter encodes the entry time as an RFC3339-formatted string under the provided key.
RFC3339NanoFormatter encodes the entry time as an RFC3339-formatted string with nanosecond precision under the provided key.
Skip constructs a no-op Field.
Stack constructs a Field that stores a stacktrace of the current goroutine under the key "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.
Tee creates a Logger that duplicates its log calls to two or more loggers.
TextNoTime omits timestamps from the serialized log entries.
TextTimeFormat sets the format for log timestamps, using the same layout strings supported by time.Parse.
Time constructs a Field with the given key and value.
Uint constructs a Field with the given key and value.
Uint64 constructs a Field with the given key and value.
Uintptr constructs a Field with the given key and value.
UnixNanoFormatter encodes the entry time as a single int64 with nanosecond precision under the provided key.

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

# Variables

Discard is a convenience wrapper around ioutil.Discard.
DiscardOutput is an Option that discards logger output.

# Structs

AtomicLevel wraps an atomically change-able Level value.
A CheckedMessage is the result of a call to Logger.Check, which allows especially performance-sensitive applications to avoid allocations for disabled or heavily sampled log levels.
Entry
An Entry represents a complete log message.
A Field is a marshaling operation used to add a key-value pair to a logger's context.
Meta is implementation-agnostic state management for Loggers.

# Interfaces

Encoder is a format-agnostic interface for all log entry marshalers.
JSONOption is used to set options for a JSON encoder.
KeyValue is an encoding-agnostic interface to add structured data to the logging context.
LevelEnabler decides whether a given logging level is enabled when logging a message.
A Logger enables leveled, structured logging.
LogMarshaler allows user-defined types to efficiently add themselves to the logging context, and to selectively omit information which shouldn't be included in logs (e.g., passwords).
Option is used to set options for the logger.
A TextOption is used to set options for a text encoder.
A WriteFlusher is an io.Writer that can also flush any buffered data.
A WriteSyncer is an io.Writer that can also flush any buffered data.

# Type aliases

A Hook is executed each time the logger writes an Entry.
A Level is a logging priority.
LevelEnablerFunc is a convenient way to implement LevelEnabler around an anonymous function.
A LevelFormatter defines how to convert an entry's logging level into a Field.
LogMarshalerFunc is a type adapter that allows using a function as a LogMarshaler.
A MessageFormatter defines how to convert a log message into a Field.
A TimeFormatter defines how to convert the time of a log entry into a Field.