OnWrite implements the OnWrite method to keep CheckWriteAction compatible
with the new CheckWriteHook interface which deprecates CheckWriteAction.
type CheckWriteHook interface {
OnWrite(*CheckedEntry, []Field)
CheckWriteHook is a custom action that may be executed after an entry is
written.
Register one on a CheckedEntry with the After method.
if ce := logger.Check(...); ce != nil {
ce = ce.After(hook)
ce.Write(...)
You can configure the hook for Fatal log statements at the logger level with
the zap.WithFatalHook option.
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 After on a
nil *CheckedEntry. References are returned to a pool after Write, and MUST
NOT be retained after calling their Write method.
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 (ce *CheckedEntry) After(ent Entry, hook CheckWriteHook) *CheckedEntry
After sets this CheckEntry's CheckWriteHook, which will be called after this
log entry has been written. It's safe to call this on nil CheckedEntry
references.
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.
Deprecated: Use CheckedEntry.After instead.
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.
NewTicker(time.Duration) *time.Ticker
Clock is a source of time for logged entries.
With([]Field) Core
Check(Entry, *CheckedEntry) *CheckedEntry
Write(Entry, []Field) error
Sync() error
Core is a minimal, fast logger interface. It's designed for library authors
to wrap in a more user-friendly API.
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 NewLazyWith(core Core, fields []Field) Core
NewLazyWith wraps a Core with a "lazy" Core that will only encode fields if
the logger is written to (or is further chained in a lon-lazy manner).
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 zap'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(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 NewTee(cores ...Core) Core
NewTee creates a Core that duplicates log entries into two or more
underlying Cores.
Calling it with a single Core returns the input unchanged, and calling
it with no input returns a no-op Core.
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 func(time.Duration, PrimitiveArrayEncoder)
A DurationEncoder serializes a time.Duration to a primitive type.
This function must make exactly one call
to a PrimitiveArrayEncoder's Append* method.
func (e *DurationEncoder) UnmarshalText(text []byte) error
UnmarshalText unmarshals text to a DurationEncoder. "string" is unmarshaled
to StringDurationEncoder, and anything else is unmarshaled to
NanosDurationEncoder.
ObjectEncoder
Clone() Encoder
EncodeEntry(Entry, []Field) (*buffer.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(cfg EncoderConfig) 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(cfg EncoderConfig) 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 EncoderConfig struct {
MessageKey string `json:"messageKey" yaml:"messageKey"`
LevelKey string `json:"levelKey" yaml:"levelKey"`
TimeKey string `json:"timeKey" yaml:"timeKey"`
NameKey string `json:"nameKey" yaml:"nameKey"`
CallerKey string `json:"callerKey" yaml:"callerKey"`
FunctionKey string `json:"functionKey" yaml:"functionKey"`
StacktraceKey string `json:"stacktraceKey" yaml:"stacktraceKey"`
SkipLineEnding bool `json:"skipLineEnding" yaml:"skipLineEnding"`
LineEnding string `json:"lineEnding" yaml:"lineEnding"`
EncodeLevel LevelEncoder `json:"levelEncoder" yaml:"levelEncoder"`
EncodeTime TimeEncoder `json:"timeEncoder" yaml:"timeEncoder"`
EncodeDuration DurationEncoder `json:"durationEncoder" yaml:"durationEncoder"`
EncodeCaller CallerEncoder `json:"callerEncoder" yaml:"callerEncoder"`
EncodeName NameEncoder `json:"nameEncoder" yaml:"nameEncoder"`
NewReflectedEncoder func(io.Writer) ReflectedEncoder `json:"-" yaml:"-"`
ConsoleSeparator string `json:"consoleSeparator" yaml:"consoleSeparator"`
An EncoderConfig allows users to configure the concrete encoders supplied by
zapcore.
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.
func NewEntryCaller(pc uintptr, file string, line int, ok bool) EntryCaller
NewEntryCaller makes an EntryCaller from the return signature of
runtime.Caller.
func (ec EntryCaller) FullPath() string
FullPath returns a /full/path/to/package/file:line description of the
caller.
func (ec EntryCaller) TrimmedPath() string
TrimmedPath returns a package/file:line description of the caller,
preserving only the leaf directory name and file name.
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 (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 (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 uint8
A FieldType indicates which member of the Field union struct should be used
and how it should be serialized.
const (
UnknownType FieldType = iota
ArrayMarshalerType
ObjectMarshalerType
BinaryType
BoolType
ByteStringType
Complex128Type
Complex64Type
DurationType
Float64Type
Float32Type
Int64Type
Int32Type
Int16Type
Int8Type
StringType
TimeType
TimeFullType
Uint64Type
Uint32Type
Uint16Type
Uint8Type
UintptrType
ReflectType
NamespaceType
StringerType
ErrorType
SkipType
InlineMarshalerType
const (
DebugLevel Level = iota - 1
InfoLevel
WarnLevel
ErrorLevel
DPanicLevel
PanicLevel
FatalLevel
InvalidLevel = _maxLevel + 1
func LevelOf(enab LevelEnabler) Level
LevelOf reports the minimum enabled log level for the given LevelEnabler
from Zap's supported log levels, or InvalidLevel if none of them are
enabled.
A LevelEnabler may implement a 'Level() Level' method to override the
behavior of this function.
func (c *core) Level() Level {
return c.currentLevel
It is recommended that Core implementations that wrap other cores use
LevelOf to retrieve the level of the wrapped core. For example,
func (c *coreWrapper) Level() Level {
return zapcore.LevelOf(c.wrappedCore)
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 (l Level) MarshalText() ([]byte, error)
MarshalText marshals the Level to text. Note that the text representation
drops the -Level suffix (see example).
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.
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 LevelEncoder func(Level, PrimitiveArrayEncoder)
A LevelEncoder serializes a Level to a primitive type.
This function must make exactly one call
to a PrimitiveArrayEncoder's Append* method.
func (e *LevelEncoder) UnmarshalText(text []byte) error
UnmarshalText unmarshals text to a LevelEncoder. "capital" is unmarshaled to
CapitalLevelEncoder, "coloredCapital" is unmarshaled to CapitalColorLevelEncoder,
"colored" is unmarshaled to LowercaseColorLevelEncoder, and anything else
is unmarshaled to LowercaseLevelEncoder.
type MapObjectEncoder struct {
Fields map[string]interface{}
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.
type NameEncoder func(string, PrimitiveArrayEncoder)
A NameEncoder serializes a period-separated logger name to a primitive
type.
This function must make exactly one call
to a PrimitiveArrayEncoder's Append* method.
func (e *NameEncoder) UnmarshalText(text []byte) error
UnmarshalText unmarshals text to a NameEncoder. Currently, everything is
unmarshaled to FullNameEncoder.
type ObjectEncoder interface {
AddArray(key string, marshaler ArrayMarshaler) error
AddObject(key string, marshaler ObjectMarshaler) error
AddBinary(key string, value []byte)
AddByteString(key string, value []byte)
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(key string, value interface{}) error
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).
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 zap.Object is used or when
passed directly to zap.Any. It is not used when reflection-based
encoding is used.
type ObjectMarshalerFunc func(ObjectEncoder) error
ObjectMarshalerFunc is a type adapter that turns a function into an
ObjectMarshaler.
AppendBool(bool)
AppendByteString([]byte)
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 interface {
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.
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
zapcore.SamplerHook(func(ent zapcore.Entry, dec zapcore.SamplingDecision) {
if dec&zapcore.LogDropped > 0 {
dropped.Inc()
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 SamplingDecision = 1 << iota
LogSampled
type TimeEncoder func(time.Time, PrimitiveArrayEncoder)
A TimeEncoder serializes a time.Time to a primitive type.
This function must make exactly one call
to a PrimitiveArrayEncoder's Append* method.
func TimeEncoderOfLayout(layout string) TimeEncoder
TimeEncoderOfLayout returns TimeEncoder which serializes a time.Time using
given layout.
func (e *TimeEncoder) UnmarshalText(text []byte) error
UnmarshalText unmarshals text to a TimeEncoder.
"rfc3339nano" and "RFC3339Nano" are unmarshaled to RFC3339NanoTimeEncoder.
"rfc3339" and "RFC3339" are unmarshaled to RFC3339TimeEncoder.
"iso8601" and "ISO8601" are unmarshaled to ISO8601TimeEncoder.
"millis" is unmarshaled to EpochMillisTimeEncoder.
"nanos" is unmarshaled to EpochNanosEncoder.
Anything else is unmarshaled to EpochTimeEncoder.
func (e *TimeEncoder) UnmarshalYAML(unmarshal func(interface{}) error) error
UnmarshalYAML unmarshals YAML to a TimeEncoder.
If value is an object with a "layout" field, it will be unmarshaled to TimeEncoder with given layout.
timeEncoder:
layout: 06/01/02 03:04pm
If value is string, it uses UnmarshalText.
timeEncoder: iso8601
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 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(ws ...WriteSyncer) WriteSyncer
NewMultiWriteSyncer creates a WriteSyncer that duplicates its writes
and sync calls, much like io.MultiWriter.
go.dev uses cookies from Google to deliver and enhance the quality of its services and to
analyze traffic.
Learn more.