zap

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: May 12, 2017 License: MIT Imports: 19 Imported by: 0

README

⚡ zap GoDoc Build Status Coverage Status

Blazing fast, structured, leveled logging in Go.

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 than other structured logging libraries 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),
)

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 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:

Library Time Bytes Allocated Objects Allocated
⚡ zap 1526 ns/op 704 B/op 2 allocs/op
⚡ zap (sugared) 2274 ns/op 1610 B/op 20 allocs/op
go-kit 5854 ns/op 2895 B/op 66 allocs/op
logrus 9117 ns/op 6092 B/op 78 allocs/op
lion 9408 ns/op 5807 B/op 63 allocs/op
apex/log 17007 ns/op 3832 B/op 65 allocs/op
log15 21290 ns/op 5632 B/op 93 allocs/op

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

Library Time Bytes Allocated Objects Allocated
⚡ zap 446 ns/op 0 B/op 0 allocs/op
⚡ zap (sugared) 599 ns/op 80 B/op 2 allocs/op
lion 5231 ns/op 4074 B/op 38 allocs/op
go-kit 6424 ns/op 3046 B/op 52 allocs/op
logrus 7578 ns/op 4564 B/op 63 allocs/op
apex/log 15697 ns/op 2898 B/op 51 allocs/op
log15 15879 ns/op 2642 B/op 44 allocs/op

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

Library Time Bytes Allocated Objects Allocated
⚡ zap 418 ns/op 0 B/op 0 allocs/op
standard library 524 ns/op 80 B/op 2 allocs/op
⚡ zap (sugared) 628 ns/op 80 B/op 2 allocs/op
go-kit 1011 ns/op 656 B/op 13 allocs/op
lion 1382 ns/op 1224 B/op 10 allocs/op
logrus 2263 ns/op 1505 B/op 27 allocs/op
apex/log 3198 ns/op 584 B/op 11 allocs/op
log15 5787 ns/op 1592 B/op 26 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.


Released under the MIT License.

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.

Documentation

Overview

Package zap provides fast, structured, leveled logging in Go.

Index

Constants

View Source
const (
	// DebugLevel logs are typically voluminous, and are usually disabled in
	// production.
	DebugLevel = zapcore.DebugLevel
	// InfoLevel is the default logging priority.
	InfoLevel = zapcore.InfoLevel
	// WarnLevel logs are more important than Info, but don't need individual
	// human review.
	WarnLevel = zapcore.WarnLevel
	// ErrorLevel logs are high-priority. If an application is running smoothly,
	// it shouldn't generate any error-level logs.
	ErrorLevel = zapcore.ErrorLevel
	// DPanicLevel logs are particularly important errors. In development the
	// logger panics after writing the message.
	DPanicLevel = zapcore.DPanicLevel
	// PanicLevel logs a message, then panics.
	PanicLevel = zapcore.PanicLevel
	// FatalLevel logs a message, then calls os.Exit(1).
	FatalLevel = zapcore.FatalLevel
)

Variables

This section is empty.

Functions

func Any

func Any(key string, value interface{}) zapcore.Field

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.

Since byte/uint8 and rune/int32 are aliases, Any can't differentiate between them. To minimize suprise, []byte values are treated as binary blobs, byte values are treated as uint8, and runes are always treated as integers.

func Array

func Array(key string, val zapcore.ArrayMarshaler) zapcore.Field

Array constructs a field with the given key and ArrayMarshaler. It provides a flexible, but still type-safe and efficient, way to add array-like types to the logging context. The struct's MarshalLogArray method is called lazily.

func Binary

func Binary(key string, val []byte) zapcore.Field

Binary constructs a field that carries an opaque binary blob.

Binary data is serialized in an encoding-appropriate format. For example, zap's JSON encoder base64-encodes binary blobs. To log UTF-8 encoded text, use ByteString.

func Bool

func Bool(key string, val bool) zapcore.Field

Bool constructs a field that carries a bool.

func Bools

func Bools(key string, bs []bool) zapcore.Field

Bools constructs a field that carries a slice of bools.

func ByteString

func ByteString(key string, val []byte) zapcore.Field

ByteString constructs a field that carries UTF-8 encoded text as a []byte. To log opaque binary blobs (which aren't necessarily valid UTF-8), use Binary.

func ByteStrings

func ByteStrings(key string, bss [][]byte) zapcore.Field

ByteStrings constructs a field that carries a slice of []byte, each of which must be UTF-8 encoded text.

func CombineWriteSyncers

func CombineWriteSyncers(writers ...zapcore.WriteSyncer) zapcore.WriteSyncer

CombineWriteSyncers combines multiple WriteSyncers into a single, locked WriteSyncer.

func Complex128

func Complex128(key string, val complex128) zapcore.Field

Complex128 constructs a field that carries a complex number. Unlike most numeric fields, this costs an allocation (to convert the complex128 to interface{}).

func Complex128s

func Complex128s(key string, nums []complex128) zapcore.Field

Complex128s constructs a field that carries a slice of complex numbers.

func Complex64

func Complex64(key string, val complex64) zapcore.Field

Complex64 constructs a field that carries a complex number. Unlike most numeric fields, this costs an allocation (to convert the complex64 to interface{}).

func Complex64s

func Complex64s(key string, nums []complex64) zapcore.Field

Complex64s constructs a field that carries a slice of complex numbers.

func Duration

func Duration(key string, val time.Duration) zapcore.Field

Duration constructs a field with the given key and value. The encoder controls how the duration is serialized.

func Durations

func Durations(key string, ds []time.Duration) zapcore.Field

Durations constructs a field that carries a slice of time.Durations.

func Error

func Error(err error) zapcore.Field

Error is shorthand for the common idiom NamedError("error", err).

func Errors

func Errors(key string, errs []error) zapcore.Field

Errors constructs a field that carries a slice of errors.

func Float32

func Float32(key string, val float32) zapcore.Field

Float32 constructs a field that carries a float32. The way the floating-point value is represented is encoder-dependent, so marshaling is necessarily lazy.

func Float32s

func Float32s(key string, nums []float32) zapcore.Field

Float32s constructs a field that carries a slice of floats.

func Float64

func Float64(key string, val float64) zapcore.Field

Float64 constructs a field that carries a float64. The way the floating-point value is represented is encoder-dependent, so marshaling is necessarily lazy.

func Float64s

func Float64s(key string, nums []float64) zapcore.Field

Float64s constructs a field that carries a slice of floats.

func Int

func Int(key string, val int) zapcore.Field

Int constructs a field with the given key and value.

func Int16

func Int16(key string, val int16) zapcore.Field

Int16 constructs a field with the given key and value.

func Int16s

func Int16s(key string, nums []int16) zapcore.Field

Int16s constructs a field that carries a slice of integers.

func Int32

func Int32(key string, val int32) zapcore.Field

Int32 constructs a field with the given key and value.

func Int32s

func Int32s(key string, nums []int32) zapcore.Field

Int32s constructs a field that carries a slice of integers.

func Int64

func Int64(key string, val int64) zapcore.Field

Int64 constructs a field with the given key and value.

func Int64s

func Int64s(key string, nums []int64) zapcore.Field

Int64s constructs a field that carries a slice of integers.

func Int8

func Int8(key string, val int8) zapcore.Field

Int8 constructs a field with the given key and value.

func Int8s

func Int8s(key string, nums []int8) zapcore.Field

Int8s constructs a field that carries a slice of integers.

func Ints

func Ints(key string, nums []int) zapcore.Field

Ints constructs a field that carries a slice of integers.

func LevelFlag

func LevelFlag(name string, defaultLevel zapcore.Level, usage string) *zapcore.Level

LevelFlag defines a Level flag with specified name, default value and usage string. The return value is the address of a Level value that stores the value of the flag.

Note that you can also use any non-nil *Level as a flag.Value.

func NamedError

func NamedError(key string, err error) zapcore.Field

NamedError constructs a field that lazily stores err.Error() under the provided key. Errors which also implement fmt.Formatter (like those produced by github.com/pkg/errors) will also have their verbose representation stored under key+"Verbose". If passed a nil error, the field is a no-op.

For the common case in which the key is simply "error", the Error function is shorter and less repetitive.

func Namespace

func Namespace(key string) zapcore.Field

Namespace creates a named, isolated scope within the logger's context. All subsequent fields will be added to the new namespace.

This helps prevent key collisions when injecting loggers into sub-components or third-party libraries.

func NewDevelopmentEncoderConfig

func NewDevelopmentEncoderConfig() zapcore.EncoderConfig

NewDevelopmentEncoderConfig returns an opinionated EncoderConfig for development environments.

func NewProductionEncoderConfig

func NewProductionEncoderConfig() zapcore.EncoderConfig

NewProductionEncoderConfig returns an opinionated EncoderConfig for production environments.

func NewStdLog

func NewStdLog(l *Logger) *log.Logger

NewStdLog returns a *log.Logger which writes to the supplied zap Logger at InfoLevel. To redirect the standard library's package-global logging functions, use RedirectStdLog instead.

func Object

func Object(key string, val zapcore.ObjectMarshaler) zapcore.Field

Object constructs a field with the given key and ObjectMarshaler. It provides a flexible, but still type-safe and efficient, way to add map- or struct-like user-defined types to the logging context. The struct's MarshalLogObject method is called lazily.

func Open

func Open(paths ...string) (zapcore.WriteSyncer, func(), error)

Open is a high-level wrapper that takes a variadic number of paths, opens or creates each of the specified files, and combines them into a locked WriteSyncer. It also returns any error encountered and a function to close any opened files.

Passing no paths returns a no-op WriteSyncer. The special paths "stdout" and "stderr" are interpreted as os.Stdout and os.Stderr, respectively.

func RedirectStdLog

func RedirectStdLog(l *Logger) func()

RedirectStdLog redirects output from the standard library's package-global logger to the supplied logger at InfoLevel. Since zap already handles caller annotations, timestamps, etc., it automatically disables the standard library's annotations and prefixing.

It returns a function to restore the original prefix and flags and reset the standard library's output to os.Stdout.

func Reflect

func Reflect(key string, val interface{}) zapcore.Field

Reflect constructs a field with the given key and an arbitrary object. It uses an encoding-appropriate, reflection-based function to lazily serialize nearly any object into the logging context, but it's relatively slow and allocation-heavy. Outside tests, Any is always a better choice.

If encoding fails (e.g., trying to serialize a map[int]string to JSON), Reflect includes the error message in the final log output.

func RegisterEncoder

func RegisterEncoder(name string, constructor func(zapcore.EncoderConfig) (zapcore.Encoder, error)) error

RegisterEncoder registers an encoder constructor for the given name.

If an encoder with the same name already exists, this will return an error. By default, the encoders "json" and "console" are registered.

func ReplaceGlobals

func ReplaceGlobals(logger *Logger) func()

ReplaceGlobals replaces the global Logger and the SugaredLogger, and returns a function to restore the original values.

It's safe for concurrent use.

func Skip

func Skip() zapcore.Field

Skip constructs a no-op field.

func Stack

func Stack(key string) zapcore.Field

Stack constructs a field that stores a stacktrace of the current goroutine under provided key. Keep in mind that taking a stacktrace is eager and expensive (relatively speaking); this function both makes an allocation and takes about two microseconds.

func String

func String(key string, val string) zapcore.Field

String constructs a field with the given key and value.

func Stringer

func Stringer(key string, val fmt.Stringer) zapcore.Field

Stringer constructs a field with the given key and the output of the value's String method. The Stringer's String method is called lazily.

func Strings

func Strings(key string, ss []string) zapcore.Field

Strings constructs a field that carries a slice of strings.

func Time

func Time(key string, val time.Time) zapcore.Field

Time constructs a zapcore.Field with the given key and value. The encoder controls how the time is serialized.

func Times

func Times(key string, ts []time.Time) zapcore.Field

Times constructs a field that carries a slice of time.Times.

func Uint

func Uint(key string, val uint) zapcore.Field

Uint constructs a field with the given key and value.

func Uint16

func Uint16(key string, val uint16) zapcore.Field

Uint16 constructs a field with the given key and value.

func Uint16s

func Uint16s(key string, nums []uint16) zapcore.Field

Uint16s constructs a field that carries a slice of unsigned integers.

func Uint32

func Uint32(key string, val uint32) zapcore.Field

Uint32 constructs a field with the given key and value.

func Uint32s

func Uint32s(key string, nums []uint32) zapcore.Field

Uint32s constructs a field that carries a slice of unsigned integers.

func Uint64

func Uint64(key string, val uint64) zapcore.Field

Uint64 constructs a field with the given key and value.

func Uint64s

func Uint64s(key string, nums []uint64) zapcore.Field

Uint64s constructs a field that carries a slice of unsigned integers.

func Uint8

func Uint8(key string, val uint8) zapcore.Field

Uint8 constructs a field with the given key and value.

func Uint8s

func Uint8s(key string, nums []uint8) zapcore.Field

Uint8s constructs a field that carries a slice of unsigned integers.

func Uintptr

func Uintptr(key string, val uintptr) zapcore.Field

Uintptr constructs a field with the given key and value.

func Uintptrs

func Uintptrs(key string, us []uintptr) zapcore.Field

Uintptrs constructs a field that carries a slice of pointer addresses.

func Uints

func Uints(key string, nums []uint) zapcore.Field

Uints constructs a field that carries a slice of unsigned integers.

Types

type AtomicLevel

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

An AtomicLevel is an atomically changeable, dynamic logging level. It lets you safely change the log level of a tree of loggers (the root logger and any children created by adding context) at runtime.

The AtomicLevel itself is an http.Handler that serves a JSON endpoint to alter its level.

AtomicLevels must be created with the NewAtomicLevel constructor to allocate their internal atomic pointer.

func NewAtomicLevel

func NewAtomicLevel() AtomicLevel

NewAtomicLevel creates an AtomicLevel with InfoLevel and above logging enabled.

func NewAtomicLevelAt added in v1.3.0

func NewAtomicLevelAt(l zapcore.Level) AtomicLevel

NewAtomicLevelAt is a convienence function that creates an AtomicLevel and then calls SetLevel with the given level.

func (AtomicLevel) Enabled

func (lvl AtomicLevel) Enabled(l zapcore.Level) bool

Enabled implements the zapcore.LevelEnabler interface, which allows the AtomicLevel to be used in place of traditional static levels.

func (AtomicLevel) Level

func (lvl AtomicLevel) Level() zapcore.Level

Level returns the minimum enabled log level.

func (AtomicLevel) MarshalText added in v1.3.0

func (lvl AtomicLevel) MarshalText() (text []byte, err error)

MarshalText marshals the AtomicLevel to a byte slice. It uses the same text representation as the static zapcore.Levels ("debug", "info", "warn", "error", "dpanic", "panic", and "fatal").

func (AtomicLevel) ServeHTTP

func (lvl AtomicLevel) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP is a simple JSON endpoint that can report on or change the current logging level.

GET requests return a JSON description of the current logging level. PUT requests change the logging level and expect a payload like:

{"level":"info"}

It's perfectly safe to change the logging level while a program is running.

func (AtomicLevel) SetLevel

func (lvl AtomicLevel) SetLevel(l zapcore.Level)

SetLevel alters the logging level.

func (AtomicLevel) String added in v1.4.0

func (lvl AtomicLevel) String() string

String returns the string representation of the underlying Level.

func (*AtomicLevel) UnmarshalText

func (lvl *AtomicLevel) UnmarshalText(text []byte) error

UnmarshalText unmarshals the text to an AtomicLevel. It uses the same text representations as the static zapcore.Levels ("debug", "info", "warn", "error", "dpanic", "panic", and "fatal").

type Config

type Config struct {
	// Level is the minimum enabled logging level. Note that this is a dynamic
	// level, so calling Config.Level.SetLevel will atomically change the log
	// level of all loggers descended from this config. The zero value is
	// InfoLevel.
	Level AtomicLevel `json:"level" yaml:"level"`
	// Development puts the logger in development mode, which changes the
	// behavior of DPanicLevel and takes stacktraces more liberally.
	Development bool `json:"development" yaml:"development"`
	// DisableCaller stops annotating logs with the calling function's file
	// name and line number. By default, all logs are annotated.
	DisableCaller bool `json:"disableCaller" yaml:"disableCaller"`
	// DisableStacktrace completely disables automatic stacktrace capturing. By
	// default, stacktraces are captured for WarnLevel and above logs in
	// development and ErrorLevel and above in production.
	DisableStacktrace bool `json:"disableStacktrace" yaml:"disableStacktrace"`
	// Sampling sets a sampling policy. A nil SamplingConfig disables sampling.
	Sampling *SamplingConfig `json:"sampling" yaml:"sampling"`
	// Encoding sets the logger's encoding. Valid values are "json" and
	// "console".
	Encoding string `json:"encoding" yaml:"encoding"`
	// EncoderConfig sets options for the chosen encoder. See
	// zapcore.EncoderConfig for details.
	EncoderConfig zapcore.EncoderConfig `json:"encoderConfig" yaml:"encoderConfig"`
	// OutputPaths is a list of paths to write logging output to. See Open for
	// details.
	OutputPaths []string `json:"outputPaths" yaml:"outputPaths"`
	// ErrorOutputPaths is a list of paths to write internal logger errors to.
	// The default is standard error.
	ErrorOutputPaths []string `json:"errorOutputPaths" yaml:"errorOutputPaths"`
	// InitialFields is a collection of fields to add to the root logger.
	InitialFields map[string]interface{} `json:"initialFields" yaml:"initialFields"`
}

Config offers a declarative way to construct a logger.

It doesn't do anything that can't be done with New, Options, and the various zapcore.WriteSyncer and zapcore.Core wrappers, but it's a simpler way to toggle common options.

func NewDevelopmentConfig

func NewDevelopmentConfig() Config

NewDevelopmentConfig is a reasonable development configuration. Logging is enabled at DebugLevel and above.

It enables development mode (which makes DPanicLevel logs panic), uses a console encoder, writes to standard error, and disables sampling. Stacktraces are automatically included on logs of WarnLevel and above.

func NewProductionConfig

func NewProductionConfig() Config

NewProductionConfig is the recommended production configuration. Logging is enabled at InfoLevel and above.

It uses a JSON encoder, writes to standard error, and enables sampling. Stacktraces are automatically included on logs of ErrorLevel and above.

func (Config) Build

func (cfg Config) Build(opts ...Option) (*Logger, error)

Build constructs a logger from the Config and Options.

type LevelEnablerFunc

type LevelEnablerFunc func(zapcore.Level) bool

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

func (LevelEnablerFunc) Enabled

func (f LevelEnablerFunc) Enabled(lvl zapcore.Level) bool

Enabled calls the wrapped function.

type Logger

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

A Logger provides fast, leveled, structured logging. All methods are safe for concurrent use.

If you'd prefer a slower but less verbose logger, see the SugaredLogger.

func L

func L() *Logger

L returns the global Logger, which can be reconfigured with ReplaceGlobals.

It's safe for concurrent use.

func New

func New(core zapcore.Core, options ...Option) *Logger

New constructs a new Logger from the provided zapcore.Core and Options. If the passed zapcore.Core is nil, we fall back to using a no-op implementation.

This is the most flexible way to construct a Logger, but also the most verbose. For typical use cases, NewProduction and NewDevelopment are more convenient.

func NewDevelopment

func NewDevelopment(options ...Option) (*Logger, error)

NewDevelopment builds a development Logger that writes DebugLevel and above logs to standard error in a human-friendly format.

It's a shortcut for NewDevelopmentConfig().Build(...Option).

func NewNop

func NewNop() *Logger

NewNop returns a no-op Logger. It never writes out logs or internal errors, and it never runs user-defined hooks.

Using WithOptions to replace the Core or error output of a no-op Logger can re-enable logging.

func NewProduction

func NewProduction(options ...Option) (*Logger, error)

NewProduction builds a sensible production Logger that writes InfoLevel and above logs to standard error as JSON.

It's a shortcut for NewProductionConfig().Build(...Option).

func (*Logger) Check

func (log *Logger) Check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry

Check returns a CheckedEntry if logging a message at the specified level is enabled. It's a completely optional optimization; in high-performance applications, Check can help avoid allocating a slice to hold fields.

func (*Logger) Core

func (log *Logger) Core() zapcore.Core

Core returns the underlying zapcore.Core.

func (*Logger) DPanic

func (log *Logger) DPanic(msg string, fields ...zapcore.Field)

DPanic logs a message at DPanicLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

If the logger is in development mode, it then panics (DPanic means "development panic"). This is useful for catching errors that are recoverable, but shouldn't ever happen.

func (*Logger) Debug

func (log *Logger) Debug(msg string, fields ...zapcore.Field)

Debug logs a message at DebugLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*Logger) Error

func (log *Logger) Error(msg string, fields ...zapcore.Field)

Error logs a message at ErrorLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*Logger) Fatal

func (log *Logger) Fatal(msg string, fields ...zapcore.Field)

Fatal logs a message at FatalLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

The logger then calls os.Exit(1), even if logging at FatalLevel is disabled.

func (*Logger) Info

func (log *Logger) Info(msg string, fields ...zapcore.Field)

Info logs a message at InfoLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*Logger) Named

func (log *Logger) Named(s string) *Logger

Named adds a new path segment to the logger's name. Segments are joined by periods.

func (*Logger) Panic

func (log *Logger) Panic(msg string, fields ...zapcore.Field)

Panic logs a message at PanicLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

The logger then panics, even if logging at PanicLevel is disabled.

func (*Logger) Sugar

func (log *Logger) Sugar() *SugaredLogger

Sugar converts a Logger to a SugaredLogger.

func (*Logger) Sync

func (log *Logger) Sync() error

Sync flushes any buffered log entries.

func (*Logger) Warn

func (log *Logger) Warn(msg string, fields ...zapcore.Field)

Warn logs a message at WarnLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*Logger) With

func (log *Logger) With(fields ...zapcore.Field) *Logger

With creates a child logger and adds structured context to it. Fields added to the child don't affect the parent, and vice versa.

func (*Logger) WithOptions

func (log *Logger) WithOptions(opts ...Option) *Logger

WithOptions clones the current Logger, applies the supplied Options, and returns the resulting Logger. It's safe to use concurrently.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is used to set options for the logger.

func AddCaller

func AddCaller() Option

AddCaller configures the Logger to annotate each message with the filename and line number of zap's caller.

func AddCallerSkip

func AddCallerSkip(skip int) Option

AddCallerSkip increases the number of callers skipped by caller annotation (as enabled by the AddCaller option).

func AddStacktrace

func AddStacktrace(lvl zapcore.LevelEnabler) Option

AddStacktrace configures the Logger to record a stack trace for all messages at or above a given level.

func Development

func Development() Option

Development puts the logger in development mode, which alters the behavior of the DPanic method.

func ErrorOutput

func ErrorOutput(w zapcore.WriteSyncer) Option

ErrorOutput sets the destination for errors generated by the logger. The supplied WriteSyncer must be safe for concurrent use.

The Open and zapcore.Lock functions are the simplest ways to make files safe for concurrent use.

func Fields

func Fields(fs ...zapcore.Field) Option

Fields adds fields to the Logger.

func Hooks

func Hooks(hooks ...func(zapcore.Entry) error) Option

Hooks registers functions which will be called each time the Logger writes out an Entry. Repeated use of Hooks is additive.

See zapcore.RegisterHooks for details.

func WrapCore

func WrapCore(f func(zapcore.Core) zapcore.Core) Option

WrapCore wraps or replaces the Logger's underlying zapcore.Core.

type SamplingConfig

type SamplingConfig struct {
	Initial    int `json:"initial" yaml:"initial"`
	Thereafter int `json:"thereafter" yaml:"thereafter"`
}

SamplingConfig sets a sampling strategy for the logger. Sampling caps the global CPU and I/O load that logging puts on your process while attempting to preserve a representative subset of your logs.

Values configured here are per-second. See zapcore.NewSampler for details.

type SugaredLogger

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

A SugaredLogger wraps the base Logger functionality in a slower, but less verbose, API. Any Logger can be converted to a SugaredLogger with its Sugar method.

func S

func S() *SugaredLogger

S returns the global SugaredLogger, which can be reconfigured with ReplaceGlobals.

It's safe for concurrent use.

func (*SugaredLogger) DPanic

func (s *SugaredLogger) DPanic(args ...interface{})

DPanic uses fmt.Sprint to construct and log a message. In development, the logger then panics. (See DPanicLevel for details.)

func (*SugaredLogger) DPanicf

func (s *SugaredLogger) DPanicf(template string, args ...interface{})

DPanicf uses fmt.Sprintf to log a templated message. In development, the logger then panics. (See DPanicLevel for details.)

func (*SugaredLogger) DPanicw

func (s *SugaredLogger) DPanicw(msg string, keysAndValues ...interface{})

DPanicw logs a message with some additional context. In development, the logger then panics. (See DPanicLevel for details.) The variadic key-value pairs are treated as they are in With.

func (*SugaredLogger) Debug

func (s *SugaredLogger) Debug(args ...interface{})

Debug uses fmt.Sprint to construct and log a message.

func (*SugaredLogger) Debugf

func (s *SugaredLogger) Debugf(template string, args ...interface{})

Debugf uses fmt.Sprintf to log a templated message.

func (*SugaredLogger) Debugw

func (s *SugaredLogger) Debugw(msg string, keysAndValues ...interface{})

Debugw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

When debug-level logging is disabled, this is much faster than

s.With(keysAndValues).Debug(msg)

func (*SugaredLogger) Desugar

func (s *SugaredLogger) Desugar() *Logger

Desugar unwraps a SugaredLogger, exposing the original Logger.

func (*SugaredLogger) Error

func (s *SugaredLogger) Error(args ...interface{})

Error uses fmt.Sprint to construct and log a message.

func (*SugaredLogger) Errorf

func (s *SugaredLogger) Errorf(template string, args ...interface{})

Errorf uses fmt.Sprintf to log a templated message.

func (*SugaredLogger) Errorw

func (s *SugaredLogger) Errorw(msg string, keysAndValues ...interface{})

Errorw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func (*SugaredLogger) Fatal

func (s *SugaredLogger) Fatal(args ...interface{})

Fatal uses fmt.Sprint to construct and log a message, then calls os.Exit.

func (*SugaredLogger) Fatalf

func (s *SugaredLogger) Fatalf(template string, args ...interface{})

Fatalf uses fmt.Sprintf to log a templated message, then calls os.Exit.

func (*SugaredLogger) Fatalw

func (s *SugaredLogger) Fatalw(msg string, keysAndValues ...interface{})

Fatalw logs a message with some additional context, then calls os.Exit. The variadic key-value pairs are treated as they are in With.

func (*SugaredLogger) Info

func (s *SugaredLogger) Info(args ...interface{})

Info uses fmt.Sprint to construct and log a message.

func (*SugaredLogger) Infof

func (s *SugaredLogger) Infof(template string, args ...interface{})

Infof uses fmt.Sprintf to log a templated message.

func (*SugaredLogger) Infow

func (s *SugaredLogger) Infow(msg string, keysAndValues ...interface{})

Infow logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func (*SugaredLogger) Named

func (s *SugaredLogger) Named(name string) *SugaredLogger

Named adds a sub-scope to the logger's name. See Logger.Named for details.

func (*SugaredLogger) Panic

func (s *SugaredLogger) Panic(args ...interface{})

Panic uses fmt.Sprint to construct and log a message, then panics.

func (*SugaredLogger) Panicf

func (s *SugaredLogger) Panicf(template string, args ...interface{})

Panicf uses fmt.Sprintf to log a templated message, then panics.

func (*SugaredLogger) Panicw

func (s *SugaredLogger) Panicw(msg string, keysAndValues ...interface{})

Panicw logs a message with some additional context, then panics. The variadic key-value pairs are treated as they are in With.

func (*SugaredLogger) Sync

func (s *SugaredLogger) Sync() error

Sync flushes any buffered log entries.

func (*SugaredLogger) Warn

func (s *SugaredLogger) Warn(args ...interface{})

Warn uses fmt.Sprint to construct and log a message.

func (*SugaredLogger) Warnf

func (s *SugaredLogger) Warnf(template string, args ...interface{})

Warnf uses fmt.Sprintf to log a templated message.

func (*SugaredLogger) Warnw

func (s *SugaredLogger) Warnw(msg string, keysAndValues ...interface{})

Warnw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func (*SugaredLogger) With

func (s *SugaredLogger) With(args ...interface{}) *SugaredLogger

With adds a variadic number of fields to the logging context. It accepts a mix of strongly-typed zapcore.Field objects and loosely-typed key-value pairs. When processing pairs, the first element of the pair is used as the field key and the second as the field value.

For example,

 sugaredLogger.With(
   "hello", "world",
   "failure", errors.New("oh no"),
   Stack(),
   "count", 42,
   "user", User{Name: "alice"},
)

is the equivalent of

baseLogger.With(
  String("hello", "world"),
  String("failure", "oh no"),
  Stack(),
  Int("count", 42),
  Object("user", User{Name: "alice"}),
)

Note that the keys in key-value pairs should be strings. In development, passing a non-string key panics. In production, the logger is more forgiving: a separate error is logged, but the key-value pair is skipped and execution continues. Passing an orphaned key triggers similar behavior: panics in development and errors in production.

Directories

Path Synopsis
Package benchmarks contains only benchmarks comparing zap to other structured logging libraries.
Package benchmarks contains only benchmarks comparing zap to other structured logging libraries.
Package buffer provides a thin wrapper around a byte slice.
Package buffer provides a thin wrapper around a byte slice.
internal
bufferpool
Package bufferpool houses zap's shared internal buffer pool.
Package bufferpool houses zap's shared internal buffer pool.
color
Package color adds coloring functionality for TTY output.
Package color adds coloring functionality for TTY output.
exit
Package exit provides stubs so that unit tests can exercise code that calls os.Exit(1).
Package exit provides stubs so that unit tests can exercise code that calls os.Exit(1).
multierror
Package multierror provides a simple way to treat a collection of errors as a single error.
Package multierror provides a simple way to treat a collection of errors as a single error.
Package zapcore defines and implements the low-level interfaces upon which zap is built.
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 zapgrpc provides a logger that is compatible with grpclog.
Package zaptest provides helpers for testing logs.
Package zaptest provides helpers for testing logs.

Jump to

Keyboard shortcuts

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