log

package
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2023 License: MIT Imports: 26 Imported by: 8

Documentation

Index

Constants

View Source
const DefaultLineEnding = "\n"

DefaultLineEnding defines the default line ending when writing logs. Alternate line endings specified in EncoderConfig can override this behavior.

View Source
const OmitKey = ""

OmitKey defines the key to use when callers want to remove a key from log output.

Variables

View Source
var DefaultClock = systemClock{}

DefaultClock is the default clock used by Zap in operations that require time. This clock uses the system clock for all operations.

Functions

func CapitalColorLevelEncoder

func CapitalColorLevelEncoder(l Level, enc PrimitiveArrayEncoder)

CapitalColorLevelEncoder serializes a Level to an all-caps string and adds color. For example, InfoLevel is serialized to "INFO" and colored blue.

func CapitalLevelEncoder

func CapitalLevelEncoder(l Level, enc PrimitiveArrayEncoder)

CapitalLevelEncoder serializes a Level to an all-caps string. For example, InfoLevel is serialized to "INFO".

func EpochMillisTimeEncoder

func EpochMillisTimeEncoder(t time.Time, enc PrimitiveArrayEncoder)

EpochMillisTimeEncoder serializes a time.Time to a floating-point number of milliseconds since the Unix epoch.

func EpochNanosTimeEncoder

func EpochNanosTimeEncoder(t time.Time, enc PrimitiveArrayEncoder)

EpochNanosTimeEncoder serializes a time.Time to an integer number of nanoseconds since the Unix epoch.

func EpochTimeEncoder

func EpochTimeEncoder(t time.Time, enc PrimitiveArrayEncoder)

EpochTimeEncoder serializes a time.Time to a floating-point number of seconds since the Unix epoch.

func FullCallerEncoder

func FullCallerEncoder(caller EntryCaller, enc PrimitiveArrayEncoder)

FullCallerEncoder serializes a caller in /full/path/to/package/file:line format.

func FullNameEncoder

func FullNameEncoder(loggerName string, enc PrimitiveArrayEncoder)

FullNameEncoder serializes the logger name as-is.

func ISO8601TimeEncoder

func ISO8601TimeEncoder(t time.Time, enc PrimitiveArrayEncoder)

ISO8601TimeEncoder serializes a time.Time to an ISO8601-formatted string with millisecond precision.

If enc supports AppendTimeLayout(t time.Time,layout string), it's used instead of appending a pre-formatted string value.

func LowercaseColorLevelEncoder

func LowercaseColorLevelEncoder(l Level, enc PrimitiveArrayEncoder)

LowercaseColorLevelEncoder serializes a Level to a lowercase string and adds coloring. For example, InfoLevel is serialized to "info" and colored blue.

func LowercaseLevelEncoder

func LowercaseLevelEncoder(l Level, enc PrimitiveArrayEncoder)

LowercaseLevelEncoder serializes a Level to a lowercase string. For example, InfoLevel is serialized to "info".

func MillisDurationEncoder

func MillisDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder)

MillisDurationEncoder serializes a time.Duration to an integer number of milliseconds elapsed.

func NanosDurationEncoder

func NanosDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder)

NanosDurationEncoder serializes a time.Duration to an integer number of nanoseconds elapsed.

func NewStdLog

func NewStdLog(l *Logger) *log.Logger

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

func NewStdLogAt

func NewStdLogAt(l *Logger, level Level) (*log.Logger, error)

NewStdLogAt returns *log.Logger which writes to supplied logger at required level.

func RFC3339NanoTimeEncoder

func RFC3339NanoTimeEncoder(t time.Time, enc PrimitiveArrayEncoder)

RFC3339NanoTimeEncoder serializes a time.Time to an RFC3339-formatted string with nanosecond precision.

If enc supports AppendTimeLayout(t time.Time,layout string), it's used instead of appending a pre-formatted string value.

func RFC3339TimeEncoder

func RFC3339TimeEncoder(t time.Time, enc PrimitiveArrayEncoder)

RFC3339TimeEncoder serializes a time.Time to an RFC3339-formatted string.

If enc supports AppendTimeLayout(t time.Time,layout string), it's used instead of appending a pre-formatted string value.

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 log 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.Stderr.

func RedirectStdLogAt

func RedirectStdLogAt(l *Logger, level Level) (func(), error)

RedirectStdLogAt redirects output from the standard library's package-global logger to the supplied logger at the specified level. Since log 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.Stderr.

func RegisterSink

func RegisterSink(scheme string, factory func(*url.URL) (Sink, error)) error

RegisterSink registers a user-supplied factory for all sinks with a particular scheme.

All schemes must be ASCII, valid under section 3.1 of RFC 3986 (https://tools.ietf.org/html/rfc3986#section-3.1), and must not already have a factory registered. Zap automatically registers a factory for the "file" scheme.

func ReplaceGlobals

func ReplaceGlobals(logger *Logger) func()

ReplaceGlobals replaces the global Logger and SugaredLogger, and returns a function to restore the original values. It's safe for concurrent use.

func SecondsDurationEncoder

func SecondsDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder)

SecondsDurationEncoder serializes a time.Duration to a floating-point number of seconds elapsed.

func ShortCallerEncoder

func ShortCallerEncoder(caller EntryCaller, enc PrimitiveArrayEncoder)

ShortCallerEncoder serializes a caller in package/file:line format, trimming all but the final directory from the full path.

func StringDurationEncoder

func StringDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder)

StringDurationEncoder serializes a time.Duration using its built-in String method.

Types

type ArrayEncoder

type ArrayEncoder interface {
	// Built-in types.
	PrimitiveArrayEncoder

	// Time-related types.
	AppendDuration(time.Duration)
	AppendTime(time.Time)

	// Logging-specific marshalers.
	AppendArray(ArrayMarshaler) error
	AppendObject(ObjectMarshaler) error

	// AppendReflected uses reflection to serialize arbitrary objects, so it's
	// slow and allocation-heavy.
	AppendReflected(value interface{}) error
}

ArrayEncoder is a strongly-typed, encoding-agnostic interface for adding array-like objects to the logging context. Of note, it supports mixed-type arrays even though they aren't typical in Go. Like slices, ArrayEncoders aren't safe for concurrent use (though typical use shouldn't require locks).

type ArrayMarshaler

type ArrayMarshaler interface {
	MarshalLogArray(ArrayEncoder) error
}

ArrayMarshaler 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).

Note: ArrayMarshaler is only used when log.Array is used or when passed directly to log.Any. It is not used when reflection-based encoding is used.

type ArrayMarshalerFunc

type ArrayMarshalerFunc func(ArrayEncoder) error

ArrayMarshalerFunc is a type adapter that turns a function into an ArrayMarshaler.

func (ArrayMarshalerFunc) MarshalLogArray

func (f ArrayMarshalerFunc) MarshalLogArray(enc ArrayEncoder) error

MarshalLogArray calls the underlying function.

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

func NewAtomicLevelAt(l Level) AtomicLevel

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

func ParseAtomicLevel

func ParseAtomicLevel(text string) (AtomicLevel, error)

ParseAtomicLevel parses an AtomicLevel based on a lowercase or all-caps ASCII representation of the log level. If the provided ASCII representation is invalid an error is returned.

This is particularly useful when dealing with text input to configure log levels.

func (AtomicLevel) Enabled

func (lvl AtomicLevel) Enabled(l Level) bool

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

func (AtomicLevel) Level

func (lvl AtomicLevel) Level() Level

Level returns the minimum enabled log level.

func (AtomicLevel) MarshalText

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 Levels ("debug", "info", "warn", "error", "dpanic", "panic", and "fatal").

func (AtomicLevel) SetLevel

func (lvl AtomicLevel) SetLevel(l Level)

SetLevel alters the logging level.

func (AtomicLevel) String

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 Levels ("debug", "info", "warn", "error", "dpanic", "panic", and "fatal").

func (*AtomicLevel) UnmarshalYAML

func (lvl *AtomicLevel) UnmarshalYAML(value *yaml.Node) error

type AtomicLogger

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

func NewAtomic

func NewAtomic(logger *Logger) *AtomicLogger

func (*AtomicLogger) CompareAndSwapLogger

func (l *AtomicLogger) CompareAndSwapLogger(old *Logger, new *Logger) bool

func (*AtomicLogger) Logger

func (l *AtomicLogger) Logger() *Logger

func (*AtomicLogger) SetLogger

func (l *AtomicLogger) SetLogger(logger *Logger)

func (*AtomicLogger) SwapLogger

func (l *AtomicLogger) SwapLogger(logger *Logger) *Logger

type CallerEncoder

type CallerEncoder func(EntryCaller, PrimitiveArrayEncoder)

A CallerEncoder serializes an EntryCaller to a primitive type.

func (*CallerEncoder) UnmarshalText

func (e *CallerEncoder) UnmarshalText(text []byte) error

UnmarshalText unmarshals text to a CallerEncoder. "full" is unmarshalled to FullCallerEncoder and anything else is unmarshalled to ShortCallerEncoder.

type CheckWriteAction

type CheckWriteAction uint8

CheckWriteAction indicates what action to take after a log entry is processed. Actions are ordered in increasing severity.

const (
	// WriteThenNoop indicates that nothing special needs to be done. It's the
	// default behavior.
	WriteThenNoop CheckWriteAction = iota
	// WriteThenGoexit runs runtime.Goexit after Write.
	WriteThenGoexit
	// WriteThenPanic causes a panic after Write.
	WriteThenPanic
	// WriteThenFatal causes a fatal os.Exit after Write.
	WriteThenFatal
)

type CheckedEntry

type CheckedEntry struct {
	Entry
	ErrorOutput WriteSyncer
	// contains filtered or unexported fields
}

CheckedEntry is an Entry together with a collection of Cores that have already agreed to log it.

CheckedEntry references should be created by calling AddCore or Should on a nil *CheckedEntry. References are returned to a pool after Write, and MUST NOT be retained after calling their Write method.

func (*CheckedEntry) AddCore

func (ce *CheckedEntry) AddCore(ent Entry, core Core) *CheckedEntry

AddCore adds a Core that has agreed to log this CheckedEntry. It's intended to be used by Core.Check implementations, and is safe to call on nil CheckedEntry references.

func (*CheckedEntry) Should

func (ce *CheckedEntry) Should(ent Entry, should CheckWriteAction) *CheckedEntry

Should sets this CheckedEntry's CheckWriteAction, which controls whether a Core will panic or fatal after writing this log entry. Like AddCore, it's safe to call on nil CheckedEntry references.

func (*CheckedEntry) Write

func (ce *CheckedEntry) Write(fields ...Field)

Write writes the entry to the stored Cores, returns any errors, and returns the CheckedEntry reference to a pool for immediate re-use. Finally, it executes any required CheckWriteAction.

type Clock

type Clock interface {
	// Now returns the current local time.
	Now() time.Time

	// NewTicker returns *time.Ticker that holds a channel
	// that delivers "ticks" of a clock.
	NewTicker(time.Duration) *time.Ticker
}

Clock is a source of time for logged entries.

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.
	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:"disable-caller" yaml:"disable-caller"`
	// 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:"disable-stacktrace" yaml:"disable-stacktrace"`
	// Sampling sets a sampling policy. A nil SamplingConfig disables sampling.
	Sampling *SamplingConfig `json:"sampling" yaml:"sampling"`
	// Encoder sets the logger's encoder, See Encoder for details
	Encoder Encoder `json:"-" yaml:"-"`
	// OutputPaths is a list of URLs or file paths to write logging output to.
	// See Open for details.
	OutputPaths []string `json:"output-paths" yaml:"output-paths"`
	// ErrorOutputPaths is a list of URLs to write internal logger errors to.
	// The default is standard error.
	//
	// Note that this setting only affects internal errors; for sample code that
	// sends error-level logs to a different location from info- and debug-level
	// logs, see the package-level AdvancedConfiguration example.
	ErrorOutputPaths []string `json:"error-output-paths" yaml:"error-output-paths"`
	// InitialFields is a collection of fields to add to the root logger.
	InitialFields map[string]interface{} `json:"initial-fields" yaml:"initial-fields"`
}

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 WriteSyncer and Core wrappers, but it's a simpler way to toggle common options.

Note that Config intentionally supports only the most common options. More unusual logging setups (logging to network connections or message queues, splitting output between multiple files, etc.) are possible, but require direct use of the core package. For sample code, see the package-level BasicConfiguration and AdvancedConfiguration examples.

For an example showing runtime log level changes, see the documentation for AtomicLevel.

func NewDevelopmentConfig

func NewDevelopmentConfig() Config

NewDevelopmentConfig is a reasonable development logging 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 a reasonable production logging 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 ConsoleEncoderConfig

type ConsoleEncoderConfig struct {
	// Set the keys used for each log entry. If any key is empty, that portion
	// of the entry is omitted.
	DisableLevel      bool   `json:"disable-level" yaml:"disable-level"`
	DisableTime       bool   `json:"disable-time" yaml:"disable-time"`
	DisableName       bool   `json:"disable-name" yaml:"disable-name"`
	DisableCaller     bool   `json:"disable-caller" yaml:"disable-caller"`
	DisableFunction   bool   `json:"disable-function" yaml:"disable-function"`
	DisableStacktrace bool   `json:"disable-stacktrace" yaml:"disable-stacktrace"`
	SkipLineEnding    bool   `json:"skip-line-ending" yaml:"skip-line-ending"`
	LineEnding        string `json:"line-ending" yaml:"line-ending"`
	// Configure the primitive representations of common complex types. For
	// example, some users may want all time.Times serialized as floating-point
	// seconds since epoch, while others may prefer ISO8601 strings.
	EncodeLevel    LevelEncoder    `json:"level-encoder" yaml:"level-encoder"`
	EncodeTime     TimeEncoder     `json:"time-encoder" yaml:"time-encoder"`
	EncodeDuration DurationEncoder `json:"duration-encoder" yaml:"duration-encoder"`
	EncodeCaller   CallerEncoder   `json:"caller-encoder" yaml:"caller-encoder"`
	// Unlike the other primitive type encoders, EncodeName is optional. The
	// zero value falls back to FullNameEncoder.
	EncodeName NameEncoder `json:"name-encoder" yaml:"name-encoder"`
	// Configure the encoder for interface{} type objects.
	// If not provided, objects are encoded using json.Encoder
	NewReflectedEncoder func(io.Writer) ReflectedEncoder `json:"-" yaml:"-"`
	// Configures the field separator used by the console encoder. Defaults
	// to tab.
	ConsoleSeparator string `json:"console-separator" yaml:"console-separator"`
}

type Core

type Core interface {
	LevelEnabler

	// With adds structured context to the Core.
	With([]Field) Core
	// Check determines whether the supplied Entry should be logged (using the
	// embedded LevelEnabler and possibly some extra logic). If the entry
	// should be logged, the Core adds itself to the CheckedEntry and returns
	// the result.
	//
	// Callers must use Check before calling Write.
	Check(Entry, *CheckedEntry) *CheckedEntry
	// Write serializes the Entry and any Fields supplied at the log site and
	// writes them to their destination.
	//
	// If called, Write should always log the Entry and Fields; it should not
	// replicate the logic of Check.
	Write(Entry, []Field) error
	// Sync flushes buffered logs (if any).
	Sync() error
}

Core is a minimal, fast logger interface. It's designed for library authors to wrap in a more user-friendly API.

func NewCore

func NewCore(enc Encoder, ws WriteSyncer, enabler LevelEnabler) Core

NewCore creates a Core that writes logs to a WriteSyncer.

func NewIncreaseLevelCore

func NewIncreaseLevelCore(core Core, level LevelEnabler) (Core, error)

NewIncreaseLevelCore creates a core that can be used to increase the level of an existing Core. It cannot be used to decrease the logging level, as it acts as a filter before calling the underlying core. If level decreases the log level, an error is returned.

func NewNopCore

func NewNopCore() Core

NewNopCore returns a no-op Core.

func NewSampler deprecated

func NewSampler(core Core, tick time.Duration, first, thereafter int) Core

NewSampler creates a Core that samples incoming entries, which caps the CPU and I/O load of logging while attempting to preserve a representative subset of your logs.

Zap samples by logging the first N entries with a given level and message each tick. If more Entries with the same level and message are seen during the same interval, every Mth message is logged and the rest are dropped.

Keep in mind that log's sampling implementation is optimized for speed over absolute precision; under load, each tick may be slightly over- or under-sampled.

Deprecated: use NewSamplerWithOptions.

func NewSamplerWithOptions

func NewSamplerWithOptions(core Core, tick time.Duration, first, thereafter int, opts ...SamplerOption) Core

NewSamplerWithOptions creates a Core that samples incoming entries, which caps the CPU and I/O load of logging while attempting to preserve a representative subset of your logs.

Zap samples by logging the first N entries with a given level and message each tick. If more Entries with the same level and message are seen during the same interval, every Mth message is logged and the rest are dropped.

For example,

core = NewSamplerWithOptions(core, time.Second, 10, 5)

This will log the first 10 log entries with the same level and message in a one second interval as-is. Following that, it will allow through every 5th log entry with the same level and message in that interval.

If thereafter is zero, the Core will drop all log entries after the first N in that interval.

Sampler can be configured to report sampling decisions with the SamplerHook option.

Keep in mind that Zap's sampling implementation is optimized for speed over absolute precision; under load, each tick may be slightly over- or under-sampled.

func RegisterHooks

func RegisterHooks(core Core, hooks ...func(Entry) error) Core

RegisterHooks wraps a Core and runs a collection of user-defined callback hooks each time a message is logged. Execution of the callbacks is blocking.

This offers users an easy way to register simple callbacks (e.g., metrics collection) without implementing the full Core interface.

type DurationEncoder

type DurationEncoder func(time.Duration, PrimitiveArrayEncoder)

A DurationEncoder serializes a time.Duration to a primitive type.

func (*DurationEncoder) UnmarshalText

func (e *DurationEncoder) UnmarshalText(text []byte) error

UnmarshalText unmarshals text to a DurationEncoder. "string" is unmarshalled to StringDurationEncoder, and anything else is unmarshalled to NanosDurationEncoder.

type Encoder

type Encoder interface {
	ObjectEncoder

	// Clone copies the encoder, ensuring that adding fields to the copy doesn't
	// affect the original.
	Clone() Encoder

	// EncodeEntry encodes an entry and fields, along with any accumulated
	// context, into a byte buffer and returns it. Any fields that are empty,
	// including fields on the `Entry` type, should be omitted.
	EncodeEntry(Entry, []Field) (*bufferpool.Buffer, error)
}

Encoder is a format-agnostic interface for all log entry marshalers. Since log encoders don't need to support the same wide range of use cases as general-purpose marshalers, it's possible to make them faster and lower-allocation.

Implementations of the ObjectEncoder interface's methods can, of course, freely modify the receiver. However, the Clone and EncodeEntry methods will be called concurrently and shouldn't modify the receiver.

func NewConsoleEncoder

func NewConsoleEncoder(cfg ConsoleEncoderConfig) Encoder

NewConsoleEncoder creates an encoder whose output is designed for human - rather than machine - consumption. It serializes the core log entry data (message, level, timestamp, etc.) in a plain-text format and leaves the structured context as JSON.

Note that although the console encoder doesn't use the keys specified in the encoder configuration, it will omit any element whose key is set to the empty string.

func NewJSONEncoder

func NewJSONEncoder(cfg JsonEncoderConfig) Encoder

NewJSONEncoder creates a fast, low-allocation JSON encoder. The encoder appropriately escapes all field keys and values.

Note that the encoder doesn't deduplicate keys, so it's possible to produce a message like

{"foo":"bar","foo":"baz"}

This is permitted by the JSON specification, but not encouraged. Many libraries will ignore duplicate key-value pairs (typically keeping the last pair) when unmarshaling, but users should attempt to avoid adding duplicate keys.

type Entry

type Entry struct {
	Level      Level
	Time       time.Time
	LoggerName string
	Message    string
	Caller     EntryCaller
	Stack      string
}

An Entry represents a complete log message. The entry's structured context is already serialized, but the log level, time, message, and call site information are available for inspection and modification. Any fields left empty will be omitted when encoding.

Entries are pooled, so any functions that accept them MUST be careful not to retain references to them.

type EntryCaller

type EntryCaller struct {
	Defined  bool
	PC       uintptr
	File     string
	Line     int
	Function string
}

EntryCaller represents the caller of a logging function.

func NewEntryCaller

func NewEntryCaller(pc uintptr, file string, line int, ok bool) EntryCaller

NewEntryCaller makes an EntryCaller from the return signature of runtime.Caller.

func (EntryCaller) FullPath

func (ec EntryCaller) FullPath() string

FullPath returns a /full/path/to/package/file:line description of the caller.

func (EntryCaller) String

func (ec EntryCaller) String() string

String returns the full path and line number of the caller.

func (EntryCaller) TrimmedPath

func (ec EntryCaller) TrimmedPath() string

TrimmedPath returns a package/file:line description of the caller, preserving only the leaf directory name and file name.

type Field

type Field struct {
	Key       string
	Type      FieldType
	Integer   int64
	String    string
	Interface interface{}
}

A Field is a marshaling operation used to add a key-value pair to a logger's context. Most fields are lazily marshaled, so it's inexpensive to add fields to disabled debug-level log statements.

func Any

func Any(key string, value interface{}) 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 surprises, []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 ArrayMarshaler) 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) Field

Binary constructs a field that carries an opaque binary blob.

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

func Bool

func Bool(key string, val bool) Field

Bool constructs a field that carries a bool.

func Boolp

func Boolp(key string, val *bool) Field

Boolp constructs a field that carries a *bool. The returned Field will safely and explicitly represent `nil` when appropriate.

func Bools

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

Bools constructs a field that carries a slice of bools.

func ByteString

func ByteString(key string, val []byte) 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) Field

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

func Complex128

func Complex128(key string, val complex128) 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 Complex128p

func Complex128p(key string, val *complex128) Field

Complex128p constructs a field that carries a *complex128. The returned Field will safely and explicitly represent `nil` when appropriate.

func Complex128s

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

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

func Complex64

func Complex64(key string, val complex64) 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 Complex64p

func Complex64p(key string, val *complex64) Field

Complex64p constructs a field that carries a *complex64. The returned Field will safely and explicitly represent `nil` when appropriate.

func Complex64s

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

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

func Duration

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

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

func Durationp

func Durationp(key string, val *time.Duration) Field

Durationp constructs a field that carries a *time.Duration. The returned Field will safely and explicitly represent `nil` when appropriate.

func Durations

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

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

func Error

func Error(err error) Field

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

func ErrorFields

func ErrorFields(err error) []Field

func Errors

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

Errors constructs a field that carries a slice of errors.

func Float32

func Float32(key string, val float32) 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 Float32p

func Float32p(key string, val *float32) Field

Float32p constructs a field that carries a *float32. The returned Field will safely and explicitly represent `nil` when appropriate.

func Float32s

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

Float32s constructs a field that carries a slice of floats.

func Float64

func Float64(key string, val float64) 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 Float64p

func Float64p(key string, val *float64) Field

Float64p constructs a field that carries a *float64. The returned Field will safely and explicitly represent `nil` when appropriate.

func Float64s

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

Float64s constructs a field that carries a slice of floats.

func Inline

func Inline(val ObjectMarshaler) Field

Inline constructs a Field that is similar to Object, but it will add the elements of the provided ObjectMarshaler to the current namespace.

func Int

func Int(key string, val int) Field

Int constructs a field with the given key and value.

func Int16

func Int16(key string, val int16) Field

Int16 constructs a field with the given key and value.

func Int16p

func Int16p(key string, val *int16) Field

Int16p constructs a field that carries a *int16. The returned Field will safely and explicitly represent `nil` when appropriate.

func Int16s

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

Int16s constructs a field that carries a slice of integers.

func Int32

func Int32(key string, val int32) Field

Int32 constructs a field with the given key and value.

func Int32p

func Int32p(key string, val *int32) Field

Int32p constructs a field that carries a *int32. The returned Field will safely and explicitly represent `nil` when appropriate.

func Int32s

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

Int32s constructs a field that carries a slice of integers.

func Int64

func Int64(key string, val int64) Field

Int64 constructs a field with the given key and value.

func Int64p

func Int64p(key string, val *int64) Field

Int64p constructs a field that carries a *int64. The returned Field will safely and explicitly represent `nil` when appropriate.

func Int64s

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

Int64s constructs a field that carries a slice of integers.

func Int8

func Int8(key string, val int8) Field

Int8 constructs a field with the given key and value.

func Int8p

func Int8p(key string, val *int8) Field

Int8p constructs a field that carries a *int8. The returned Field will safely and explicitly represent `nil` when appropriate.

func Int8s

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

Int8s constructs a field that carries a slice of integers.

func Intp

func Intp(key string, val *int) Field

Intp constructs a field that carries a *int. The returned Field will safely and explicitly represent `nil` when appropriate.

func Ints

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

Ints constructs a field that carries a slice of integers.

func NamedError

func NamedError(key string, err error) 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) 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 Object

func Object(key string, val ObjectMarshaler) 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 Reflect

func Reflect(key string, val interface{}) 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 Skip

func Skip() Field

Skip constructs a no-op field, which is often useful when handling invalid inputs in other Field constructors.

func Stack

func Stack(key string) 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 StackSkip

func StackSkip(key string, skip int) Field

StackSkip constructs a field similarly to Stack, but also skips the given number of frames from the top of the stacktrace.

func String

func String(key string, val string) Field

String constructs a field with the given key and value.

func Stringer

func Stringer(key string, val fmt.Stringer) 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 Stringp

func Stringp(key string, val *string) Field

Stringp constructs a field that carries a *string. The returned Field will safely and explicitly represent `nil` when appropriate.

func Strings

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

Strings constructs a field that carries a slice of strings.

func Time

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

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

func Timep

func Timep(key string, val *time.Time) Field

Timep constructs a field that carries a *time.Time. The returned Field will safely and explicitly represent `nil` when appropriate.

func Times

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

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

func Uint

func Uint(key string, val uint) Field

Uint constructs a field with the given key and value.

func Uint16

func Uint16(key string, val uint16) Field

Uint16 constructs a field with the given key and value.

func Uint16p

func Uint16p(key string, val *uint16) Field

Uint16p constructs a field that carries a *uint16. The returned Field will safely and explicitly represent `nil` when appropriate.

func Uint16s

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

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

func Uint32

func Uint32(key string, val uint32) Field

Uint32 constructs a field with the given key and value.

func Uint32p

func Uint32p(key string, val *uint32) Field

Uint32p constructs a field that carries a *uint32. The returned Field will safely and explicitly represent `nil` when appropriate.

func Uint32s

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

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

func Uint64

func Uint64(key string, val uint64) Field

Uint64 constructs a field with the given key and value.

func Uint64p

func Uint64p(key string, val *uint64) Field

Uint64p constructs a field that carries a *uint64. The returned Field will safely and explicitly represent `nil` when appropriate.

func Uint64s

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

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

func Uint8

func Uint8(key string, val uint8) Field

Uint8 constructs a field with the given key and value.

func Uint8p

func Uint8p(key string, val *uint8) Field

Uint8p constructs a field that carries a *uint8. The returned Field will safely and explicitly represent `nil` when appropriate.

func Uint8s

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

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

func Uintp

func Uintp(key string, val *uint) Field

Uintp constructs a field that carries a *uint. The returned Field will safely and explicitly represent `nil` when appropriate.

func Uintptr

func Uintptr(key string, val uintptr) Field

Uintptr constructs a field with the given key and value.

func Uintptrp

func Uintptrp(key string, val *uintptr) Field

Uintptrp constructs a field that carries a *uintptr. The returned Field will safely and explicitly represent `nil` when appropriate.

func Uintptrs

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

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

func Uints

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

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

func (Field) AddTo

func (f Field) AddTo(enc ObjectEncoder)

AddTo exports a field through the ObjectEncoder interface. It's primarily useful to library authors, and shouldn't be necessary in most applications.

func (Field) Equals

func (f Field) Equals(other Field) bool

Equals returns whether two fields are equal. For non-primitive types such as errors, marshalers, or reflect types, it uses reflect.DeepEqual.

type FieldType

type FieldType uint8

A FieldType indicates which member of the Field union struct should be used and how it should be serialized.

const (
	// UnknownType is the default field type. Attempting to add it to an encoder will panic.
	UnknownType FieldType = iota
	// ArrayMarshalerType indicates that the field carries an ArrayMarshaler.
	ArrayMarshalerType
	// ObjectMarshalerType indicates that the field carries an ObjectMarshaler.
	ObjectMarshalerType
	// BinaryType indicates that the field carries an opaque binary blob.
	BinaryType
	// BoolType indicates that the field carries a bool.
	BoolType
	// ByteStringType indicates that the field carries UTF-8 encoded bytes.
	ByteStringType
	// Complex128Type indicates that the field carries a complex128.
	Complex128Type
	// Complex64Type indicates that the field carries a complex128.
	Complex64Type
	// DurationType indicates that the field carries a time.Duration.
	DurationType
	// Float64Type indicates that the field carries a float64.
	Float64Type
	// Float32Type indicates that the field carries a float32.
	Float32Type
	// Int64Type indicates that the field carries an int64.
	Int64Type
	// Int32Type indicates that the field carries an int32.
	Int32Type
	// Int16Type indicates that the field carries an int16.
	Int16Type
	// Int8Type indicates that the field carries an int8.
	Int8Type
	// StringType indicates that the field carries a string.
	StringType
	// TimeType indicates that the field carries a time.Time that is
	// representable by a UnixNano() stored as an int64.
	TimeType
	// TimeFullType indicates that the field carries a time.Time stored as-is.
	TimeFullType
	// Uint64Type indicates that the field carries an uint64.
	Uint64Type
	// Uint32Type indicates that the field carries an uint32.
	Uint32Type
	// Uint16Type indicates that the field carries an uint16.
	Uint16Type
	// Uint8Type indicates that the field carries an uint8.
	Uint8Type
	// UintptrType indicates that the field carries an uintptr.
	UintptrType
	// ReflectType indicates that the field carries an interface{}, which should
	// be serialized using reflection.
	ReflectType
	// NamespaceType signals the beginning of an isolated namespace. All
	// subsequent fields should be added to the new namespace.
	NamespaceType
	// StringerType indicates that the field carries a fmt.Stringer.
	StringerType
	// ErrorType indicates that the field carries an error.
	ErrorType
	// SkipType indicates that the field is a no-op.
	SkipType

	// InlineMarshalerType indicates that the field carries an ObjectMarshaler
	// that should be inlined.
	InlineMarshalerType
)

type FieldsError

type FieldsError struct {
	errors.Err
	// contains filtered or unexported fields
}

func NewFieldsError

func NewFieldsError(err error, fields ...Field) FieldsError

func (FieldsError) AddFields

func (e FieldsError) AddFields(fields ...Field) FieldsError

func (FieldsError) Fields

func (e FieldsError) Fields() []Field

func (FieldsError) GetField

func (e FieldsError) GetField(key string) Field

type JsonEncoderConfig

type JsonEncoderConfig struct {
	// Set the keys used for each log entry. If any key is empty, that portion
	// of the entry is omitted.
	MessageKey     string `json:"message-key" yaml:"message-key"`
	LevelKey       string `json:"level-key" yaml:"level-key"`
	TimeKey        string `json:"time-key" yaml:"time-key"`
	NameKey        string `json:"name-key" yaml:"name-key"`
	CallerKey      string `json:"caller-key" yaml:"caller-key"`
	FunctionKey    string `json:"function-key" yaml:"function-key"`
	StacktraceKey  string `json:"stacktrace-key" yaml:"stacktrace-key"`
	SkipLineEnding bool   `json:"skip-line-ending" yaml:"skip-line-ending"`
	LineEnding     string `json:"line-ending" yaml:"line-ending"`
	EscapeESC      bool   `json:"escape-esc" yaml:"escape-esc"`
	// Configure the primitive representations of common complex types. For
	// example, some users may want all time.Times serialized as floating-point
	// seconds since epoch, while others may prefer ISO8601 strings.
	EncodeLevel    LevelEncoder    `json:"level-encoder" yaml:"level-encoder"`
	EncodeTime     TimeEncoder     `json:"time-encoder" yaml:"time-encoder"`
	EncodeDuration DurationEncoder `json:"duration-encoder" yaml:"duration-encoder"`
	EncodeCaller   CallerEncoder   `json:"caller-encoder" yaml:"caller-encoder"`
	// Unlike the other primitive type encoders, EncodeName is optional. The
	// zero value falls back to FullNameEncoder.
	EncodeName NameEncoder `json:"name-encoder" yaml:"name-encoder"`
	// Configure the encoder for interface{} type objects.
	// If not provided, objects are encoded using json.Encoder
	NewReflectedEncoder func(io.Writer) ReflectedEncoder `json:"-" yaml:"-"`
}

An JsonEncoderConfig allows users to configure the concrete encoders supplied by core.

func NewDevelopmentJsonEncoderConfig

func NewDevelopmentJsonEncoderConfig() JsonEncoderConfig

NewDevelopmentJsonEncoderConfig returns an opinionated JsonEncoderConfig for development environments.

func NewProductionJsonEncoderConfig

func NewProductionJsonEncoderConfig() JsonEncoderConfig

NewProductionJsonEncoderConfig returns an opinionated JsonEncoderConfig for production environments.

type Level

type Level int8

A Level is a logging priority. Higher levels are more important.

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

func LevelFlag

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

LevelFlag uses the standard library's flag.Var to declare a global flag with the specified name, default, and usage guidance. The returned value is a pointer to the value of the flag.

If you don't want to use the flag package's global state, you can use any non-nil *Level as a flag.Value with your own *flag.FlagSet.

func ParseLevel

func ParseLevel(text string) (Level, error)

ParseLevel parses a level based on the lower-case or all-caps ASCII representation of the log level. If the provided ASCII representation is invalid an error is returned.

This is particularly useful when dealing with text input to configure log levels.

func (Level) CapitalString

func (l Level) CapitalString() string

CapitalString returns an all-caps ASCII representation of the log level.

func (Level) Enabled

func (l Level) Enabled(lvl Level) bool

Enabled returns true if the given level is at or above this level.

func (*Level) Get

func (l *Level) Get() interface{}

Get gets the level for the flag.Getter interface.

func (Level) MarshalText

func (l Level) MarshalText() ([]byte, error)

MarshalText marshals the Level to text. Note that the text representation drops the -Level suffix (see example).

func (*Level) Set

func (l *Level) Set(s string) error

Set sets the level for the flag.Value interface.

func (Level) String

func (l Level) String() string

String returns a lower-case ASCII representation of the log level.

func (*Level) UnmarshalText

func (l *Level) UnmarshalText(text []byte) error

UnmarshalText unmarshals text to a level. Like MarshalText, UnmarshalText expects the text representation of a Level to drop the -Level suffix (see example).

In particular, this makes it easy to configure logging levels using YAML, TOML, or JSON files.

type LevelEnabler

type LevelEnabler interface {
	Enabled(Level) bool
}

LevelEnabler decides whether a given logging level is enabled when logging a message.

Enablers are intended to be used to implement deterministic filters; concerns like sampling are better implemented as a Core.

Each concrete Level value implements a static LevelEnabler which returns true for itself and all higher logging levels. For example WarnLevel.Enabled() will return true for WarnLevel, ErrorLevel, DPanicLevel, PanicLevel, and FatalLevel, but return false for InfoLevel and DebugLevel.

type LevelEnablerFunc

type LevelEnablerFunc func(Level) bool

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

It's particularly useful when splitting log output between different outputs (e.g., standard error and standard out). For sample code, see the package-level AdvancedConfiguration example.

func (LevelEnablerFunc) Enabled

func (f LevelEnablerFunc) Enabled(lvl Level) bool

Enabled calls the wrapped function.

type LevelEncoder

type LevelEncoder func(Level, PrimitiveArrayEncoder)

A LevelEncoder serializes a Level to a primitive type.

func (*LevelEncoder) UnmarshalText

func (e *LevelEncoder) UnmarshalText(text []byte) error

UnmarshalText unmarshals text to a LevelEncoder. "capital" is unmarshalled to CapitalLevelEncoder, "coloredCapital" is unmarshalled to CapitalColorLevelEncoder, "colored" is unmarshalled to LowercaseColorLevelEncoder, and anything else is unmarshalled to LowercaseLevelEncoder.

type LogFields

type LogFields interface {
	Fields() []Field
}

type Logger

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

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

The Logger is designed for contexts in which every microsecond and every allocation matters, so its API intentionally favors performance and type safety over brevity. For most applications, the SugaredLogger strikes a better balance between performance and ergonomics.

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 Core, options ...Option) *Logger

New constructs a new Logger from the provided Core and Options. If the passed Core is nil, it falls 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, the highly-opinionated presets (NewProduction, NewDevelopment, and NewExample) or the Config struct are more convenient.

For sample code, see the package-level AdvancedConfiguration example.

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 NewExample

func NewExample(options ...Option) *Logger

NewExample builds a Logger that's designed for use in log's testable examples. It writes DebugLevel and above logs to standard out as JSON, but omits the timestamp and calling function to keep example output short and deterministic.

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 Level, msg string) *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() Core

Core returns the Logger's underlying Core.

func (*Logger) DPanic

func (log *Logger) DPanic(msg string, fields ...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 ...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 ...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) ErrorMsg

func (log *Logger) ErrorMsg(err string, fields ...Field) error

func (*Logger) ErrorWith

func (log *Logger) ErrorWith(msg string, err error, fields ...Field) error

ErrorWith logs a message and error at ErrorLevel, return err. 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 ...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 ...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(name string) *Logger

Named adds a new path segment to the logger's name. Segments are joined by periods. By default, Loggers are unnamed.

func (*Logger) Panic

func (log *Logger) Panic(msg string, fields ...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) SubNamed

func (log *Logger) SubNamed(name string) *Logger

func (*Logger) Sugar

func (log *Logger) Sugar() *SugaredLogger

Sugar wraps the Logger to provide a more ergonomic, but slightly slower, API. Sugaring a Logger is quite inexpensive, so it's reasonable for a single application to use both Loggers and SugaredLoggers, converting between them on the boundaries of performance-sensitive code.

func (*Logger) Sync

func (log *Logger) Sync() error

Sync calls the underlying Core's Sync method, flushing any buffered log entries. Applications should take care to call Sync before exiting.

func (*Logger) Warn

func (log *Logger) Warn(msg string, fields ...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 ...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 LoggerProvider

type LoggerProvider interface {
	Logger() *Logger

	SetLogger(logger *Logger)

	SwapLogger(logger *Logger) *Logger

	CompareAndSwapLogger(old *Logger, new *Logger) bool
}

type MapObjectEncoder

type MapObjectEncoder struct {
	// Fields contains the entire encoded log context.
	Fields map[string]interface{}
	// contains filtered or unexported fields
}

MapObjectEncoder is an ObjectEncoder backed by a simple map[string]interface{}. It's not fast enough for production use, but it's helpful in tests.

func NewMapObjectEncoder

func NewMapObjectEncoder() *MapObjectEncoder

NewMapObjectEncoder creates a new map-backed ObjectEncoder.

func (*MapObjectEncoder) AddArray

func (m *MapObjectEncoder) AddArray(key string, v ArrayMarshaler) error

AddArray implements ObjectEncoder.

func (*MapObjectEncoder) AddBinary

func (m *MapObjectEncoder) AddBinary(k string, v []byte)

AddBinary implements ObjectEncoder.

func (*MapObjectEncoder) AddBool

func (m *MapObjectEncoder) AddBool(k string, v bool)

AddBool implements ObjectEncoder.

func (*MapObjectEncoder) AddByteString

func (m *MapObjectEncoder) AddByteString(k string, v []byte)

AddByteString implements ObjectEncoder.

func (*MapObjectEncoder) AddComplex128

func (m *MapObjectEncoder) AddComplex128(k string, v complex128)

AddComplex128 implements ObjectEncoder.

func (*MapObjectEncoder) AddComplex64

func (m *MapObjectEncoder) AddComplex64(k string, v complex64)

AddComplex64 implements ObjectEncoder.

func (MapObjectEncoder) AddDuration

func (m MapObjectEncoder) AddDuration(k string, v time.Duration)

AddDuration implements ObjectEncoder.

func (*MapObjectEncoder) AddFloat32

func (m *MapObjectEncoder) AddFloat32(k string, v float32)

AddFloat32 implements ObjectEncoder.

func (*MapObjectEncoder) AddFloat64

func (m *MapObjectEncoder) AddFloat64(k string, v float64)

AddFloat64 implements ObjectEncoder.

func (*MapObjectEncoder) AddInt

func (m *MapObjectEncoder) AddInt(k string, v int)

AddInt implements ObjectEncoder.

func (*MapObjectEncoder) AddInt16

func (m *MapObjectEncoder) AddInt16(k string, v int16)

AddInt16 implements ObjectEncoder.

func (*MapObjectEncoder) AddInt32

func (m *MapObjectEncoder) AddInt32(k string, v int32)

AddInt32 implements ObjectEncoder.

func (*MapObjectEncoder) AddInt64

func (m *MapObjectEncoder) AddInt64(k string, v int64)

AddInt64 implements ObjectEncoder.

func (*MapObjectEncoder) AddInt8

func (m *MapObjectEncoder) AddInt8(k string, v int8)

AddInt8 implements ObjectEncoder.

func (*MapObjectEncoder) AddObject

func (m *MapObjectEncoder) AddObject(k string, v ObjectMarshaler) error

AddObject implements ObjectEncoder.

func (*MapObjectEncoder) AddReflected

func (m *MapObjectEncoder) AddReflected(k string, v interface{}) error

AddReflected implements ObjectEncoder.

func (*MapObjectEncoder) AddString

func (m *MapObjectEncoder) AddString(k string, v string)

AddString implements ObjectEncoder.

func (MapObjectEncoder) AddTime

func (m MapObjectEncoder) AddTime(k string, v time.Time)

AddTime implements ObjectEncoder.

func (*MapObjectEncoder) AddUint

func (m *MapObjectEncoder) AddUint(k string, v uint)

AddUint implements ObjectEncoder.

func (*MapObjectEncoder) AddUint16

func (m *MapObjectEncoder) AddUint16(k string, v uint16)

AddUint16 implements ObjectEncoder.

func (*MapObjectEncoder) AddUint32

func (m *MapObjectEncoder) AddUint32(k string, v uint32)

AddUint32 implements ObjectEncoder.

func (*MapObjectEncoder) AddUint64

func (m *MapObjectEncoder) AddUint64(k string, v uint64)

AddUint64 implements ObjectEncoder.

func (*MapObjectEncoder) AddUint8

func (m *MapObjectEncoder) AddUint8(k string, v uint8)

AddUint8 implements ObjectEncoder.

func (*MapObjectEncoder) AddUintptr

func (m *MapObjectEncoder) AddUintptr(k string, v uintptr)

AddUintptr implements ObjectEncoder.

func (*MapObjectEncoder) OpenNamespace

func (m *MapObjectEncoder) OpenNamespace(k string)

OpenNamespace implements ObjectEncoder.

type NameEncoder

type NameEncoder func(string, PrimitiveArrayEncoder)

A NameEncoder serializes a period-separated logger name to a primitive type.

func (*NameEncoder) UnmarshalText

func (e *NameEncoder) UnmarshalText(text []byte) error

UnmarshalText unmarshals text to a NameEncoder. Currently, everything is unmarshalled to FullNameEncoder.

type ObjectEncoder

type ObjectEncoder interface {
	// Logging-specific marshalers.
	AddArray(key string, marshaler ArrayMarshaler) error
	AddObject(key string, marshaler ObjectMarshaler) error

	// Built-in types.
	AddBinary(key string, value []byte)     // for arbitrary bytes
	AddByteString(key string, value []byte) // for UTF-8 encoded bytes
	AddBool(key string, value bool)
	AddComplex128(key string, value complex128)
	AddComplex64(key string, value complex64)
	AddDuration(key string, value time.Duration)
	AddFloat64(key string, value float64)
	AddFloat32(key string, value float32)
	AddInt(key string, value int)
	AddInt64(key string, value int64)
	AddInt32(key string, value int32)
	AddInt16(key string, value int16)
	AddInt8(key string, value int8)
	AddString(key, value string)
	AddTime(key string, value time.Time)
	AddUint(key string, value uint)
	AddUint64(key string, value uint64)
	AddUint32(key string, value uint32)
	AddUint16(key string, value uint16)
	AddUint8(key string, value uint8)
	AddUintptr(key string, value uintptr)

	// AddReflected uses reflection to serialize arbitrary objects, so it can be
	// slow and allocation-heavy.
	AddReflected(key string, value interface{}) error
	// OpenNamespace opens an isolated namespace where all subsequent fields will
	// be added. Applications can use namespaces to prevent key collisions when
	// injecting loggers into sub-components or third-party libraries.
	OpenNamespace(key string)
}

ObjectEncoder is a strongly-typed, encoding-agnostic interface for adding a map- or struct-like object to the logging context. Like maps, ObjectEncoders aren't safe for concurrent use (though typical use shouldn't require locks).

type ObjectMarshaler

type ObjectMarshaler interface {
	MarshalLogObject(ObjectEncoder) error
}

ObjectMarshaler 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).

Note: ObjectMarshaler is only used when log.Object is used or when passed directly to log.Any. It is not used when reflection-based encoding is used.

type ObjectMarshalerFunc

type ObjectMarshalerFunc func(ObjectEncoder) error

ObjectMarshalerFunc is a type adapter that turns a function into an ObjectMarshaler.

func (ObjectMarshalerFunc) MarshalLogObject

func (f ObjectMarshalerFunc) MarshalLogObject(enc ObjectEncoder) error

MarshalLogObject calls the underlying function.

type Option

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

An Option configures a Logger.

func AddCaller

func AddCaller() Option

AddCaller configures the Logger to annotate each message with the filename, line number, and function name of log's caller. See also WithCaller.

func AddCallerSkip

func AddCallerSkip(skip int) Option

AddCallerSkip increases the number of callers skipped by caller annotation (as enabled by the AddCaller option). When building wrappers around the Logger and SugaredLogger, supplying this Option prevents log from always reporting the wrapper code as the caller.

func AddStacktrace

func AddStacktrace(lvl LevelEnabler) Option

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

func AddSubName

func AddSubName(name string) Option

func Development

func Development() Option

Development puts the logger in development mode, which makes DPanic-level logs panic instead of simply logging an error.

func ErrorOutput

func ErrorOutput(w WriteSyncer) Option

ErrorOutput sets the destination for errors generated by the Logger. Note that this option only affects internal errors; for sample code that sends error-level logs to a different location from info- and debug-level logs, see the package-level AdvancedConfiguration example.

The supplied WriteSyncer must be safe for concurrent use. The Open and Lock functions are the simplest ways to protect files with a mutex.

func Fields

func Fields(fs ...Field) Option

Fields adds fields to the Logger.

func Hooks

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

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

Hooks are useful for simple side effects, like capturing metrics for the number of emitted logs. More complex side effects, including anything that requires access to the Entry's structured fields, should be implemented as a Core instead. See RegisterHooks for details.

func IncreaseLevel

func IncreaseLevel(lvl LevelEnabler) Option

IncreaseLevel increase the level of the logger. It has no effect if the passed in level tries to decrease the level of the logger.

func OnFatal

func OnFatal(action CheckWriteAction) Option

OnFatal sets the action to take on fatal logs.

func WithCaller

func WithCaller(enabled bool) Option

WithCaller configures the Logger to annotate each message with the filename, line number, and function name of log's caller, or not, depending on the value of enabled. This is a generalized form of AddCaller.

func WithClock

func WithClock(clock Clock) Option

WithClock specifies the clock used by the logger to determine the current time for logged entries. Defaults to the system clock with time.Now.

func WithName

func WithName(name string) Option

func WrapCore

func WrapCore(f func(Core) Core) Option

WrapCore wraps or replaces the Logger's underlying Core.

type PrimitiveArrayEncoder

type PrimitiveArrayEncoder interface {
	// Built-in types.
	AppendBool(bool)
	AppendByteString([]byte) // for UTF-8 encoded bytes
	AppendComplex128(complex128)
	AppendComplex64(complex64)
	AppendFloat64(float64)
	AppendFloat32(float32)
	AppendInt(int)
	AppendInt64(int64)
	AppendInt32(int32)
	AppendInt16(int16)
	AppendInt8(int8)
	AppendString(string)
	AppendUint(uint)
	AppendUint64(uint64)
	AppendUint32(uint32)
	AppendUint16(uint16)
	AppendUint8(uint8)
	AppendUintptr(uintptr)
}

PrimitiveArrayEncoder is the subset of the ArrayEncoder interface that deals only in Go's built-in types. It's included only so that Duration- and TimeEncoders cannot trigger infinite recursion.

type ReflectedEncoder

type ReflectedEncoder interface {
	// Encode encodes and writes to the underlying data stream.
	Encode(interface{}) error
}

ReflectedEncoder serializes log fields that can't be serialized with Zap's JSON encoder. These have the ReflectType field type. Use EncoderConfig.NewReflectedEncoder to set this.

type SamplerOption

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

SamplerOption configures a Sampler.

func SamplerHook

func SamplerHook(hook func(entry Entry, dec SamplingDecision)) SamplerOption

SamplerHook registers a function which will be called when Sampler makes a decision.

This hook may be used to get visibility into the performance of the sampler. For example, use it to track metrics of dropped versus sampled logs.

var dropped atomic.Int64
SamplerHook(func(ent Entry, dec SamplingDecision) {
  if dec&LogDropped > 0 {
    dropped.Inc()
  }
})

type SamplerOptionFunc

type SamplerOptionFunc func(*sampler)

SamplerOptionFunc wraps a func so it satisfies the SamplerOption interface.

type SamplingConfig

type SamplingConfig struct {
	Initial    int                           `json:"initial" yaml:"initial"`
	Thereafter int                           `json:"thereafter" yaml:"thereafter"`
	Hook       func(Entry, SamplingDecision) `json:"-" yaml:"-"`
}

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.

If specified, the Sampler will invoke the Hook after each decision.

Values configured here are per-second. See NewSamplerWithOptions for details.

type SamplingDecision

type SamplingDecision uint32

SamplingDecision is a decision represented as a bit field made by sampler. More decisions may be added in the future.

const (
	// LogDropped indicates that the Sampler dropped a log entry.
	LogDropped SamplingDecision = 1 << iota
	// LogSampled indicates that the Sampler sampled a log entry.
	LogSampled
)

type Sink

type Sink interface {
	WriteSyncer
	io.Closer
}

Sink defines the interface to write to and close logger destinations.

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.

Unlike the Logger, the SugaredLogger doesn't insist on structured logging. For each log level, it exposes three methods: one for loosely-typed structured logging, one for println-style formatting, and one for printf-style formatting. For example, SugaredLoggers can produce InfoLevel output with Infow ("info with" structured context), Info, or Infof.

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. Desugaring is quite inexpensive, so it's reasonable for a single application to use both Loggers and SugaredLoggers, converting between them on the boundaries of performance-sensitive code.

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

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

type TimeEncoder

type TimeEncoder func(time.Time, PrimitiveArrayEncoder)

A TimeEncoder serializes a time.Time to a primitive type.

func TimeEncoderOfLayout

func TimeEncoderOfLayout(layout string) TimeEncoder

TimeEncoderOfLayout returns TimeEncoder which serializes a time.Time using given layout.

func (*TimeEncoder) UnmarshalText

func (e *TimeEncoder) UnmarshalText(text []byte) error

UnmarshalText unmarshals text to a TimeEncoder. "rfc3339nano" and "RFC3339Nano" are unmarshalled to RFC3339NanoTimeEncoder. "rfc3339" and "RFC3339" are unmarshalled to RFC3339TimeEncoder. "iso8601" and "ISO8601" are unmarshalled to ISO8601TimeEncoder. "millis" is unmarshalled to EpochMillisTimeEncoder. "nanos" is unmarshalled to EpochNanosEncoder. Anything else is unmarshalled to EpochTimeEncoder.

func (*TimeEncoder) UnmarshalYAML

func (e *TimeEncoder) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML unmarshals YAML to a TimeEncoder. If value is an object with a "layout" field, it will be unmarshalled to TimeEncoder with given layout.

timeEncoder:
  layout: 06/01/02 03:04pm

If value is string, it uses UnmarshalText.

timeEncoder: iso8601

type WriteSyncer

type WriteSyncer interface {
	io.Writer
	Sync() error
}

A WriteSyncer is an io.Writer that can also flush any buffered data. Note that *os.File (and thus, os.Stderr and os.Stdout) implement WriteSyncer.

func AddSync

func AddSync(w io.Writer) WriteSyncer

AddSync converts an io.Writer to a WriteSyncer. It attempts to be intelligent: if the concrete type of the io.Writer implements WriteSyncer, we'll use the existing Sync method. If it doesn't, we'll add a no-op Sync.

func CombineWriteSyncers

func CombineWriteSyncers(writers ...WriteSyncer) WriteSyncer

CombineWriteSyncers is a utility that combines multiple WriteSyncers into a single, locked WriteSyncer. If no inputs are supplied, it returns a no-op WriteSyncer.

It's provided purely as a convenience; the result is no different from using NewMultiWriteSyncer and Lock individually.

func Lock

func Lock(ws WriteSyncer) WriteSyncer

Lock wraps a WriteSyncer in a mutex to make it safe for concurrent use. In particular, *os.Files must be locked before use.

func NewMultiWriteSyncer

func NewMultiWriteSyncer(ws ...WriteSyncer) WriteSyncer

NewMultiWriteSyncer creates a WriteSyncer that duplicates its writes and sync calls, much like io.MultiWriter.

func Open

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

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. It also returns any error encountered and a function to close any opened files.

Passing no URLs returns a no-op WriteSyncer. Zap handles URLs without a scheme and URLs with the "file" scheme. Third-party code may register factories for other schemes using RegisterSink.

URLs with the "file" scheme must use absolute paths on the local filesystem. No user, password, port, fragments, or query parameters are allowed, and the hostname must be empty or "localhost".

Since it's common to write logs to the local filesystem, URLs without a scheme (e.g., "/var/log/foo.log") are treated as local file paths. Without a scheme, the special paths "stdout" and "stderr" are interpreted as os.Stdout and os.Stderr. When specified without a scheme, relative file paths also work.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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