ArrayMarshalerFunc is a type adapter that turns a function into an
ArrayMarshaler. MarshalLogArray calls the underlying function.
ArrayMarshalerFunc : ArrayMarshaler
A BufferedWriteSyncer is a WriteSyncer that buffers writes in-memory before
flushing them to a wrapped WriteSyncer after reaching some limit, or at some
fixed interval--whichever comes first.
BufferedWriteSyncer is safe for concurrent use. You don't need to use
zapcore.Lock for WriteSyncers with BufferedWriteSyncer.
To set up a BufferedWriteSyncer, construct a WriteSyncer for your log
destination (*os.File is a valid WriteSyncer), wrap it with
BufferedWriteSyncer, and defer a Stop() call for when you no longer need the
object.
func main() {
ws := ... // your log destination
bws := &zapcore.BufferedWriteSyncer{WS: ws}
defer bws.Stop()
// ...
core := zapcore.NewCore(enc, bws, lvl)
logger := zap.New(core)
// ...
}
By default, a BufferedWriteSyncer will buffer up to 256 kilobytes of logs,
waiting at most 30 seconds between flushes.
You can customize these parameters by setting the Size or FlushInterval
fields.
For example, the following buffers up to 512 kB of logs before flushing them
to Stderr, with a maximum of one minute between each flush.
ws := &BufferedWriteSyncer{
WS: os.Stderr,
Size: 512 * 1024, // 512 kB
FlushInterval: time.Minute,
}
defer ws.Stop() Clock, if specified, provides control of the source of time for the
writer.
Defaults to the system clock. FlushInterval specifies how often the writer should flush data if
there have been no writes.
Defaults to 30 seconds if unspecified. Size specifies the maximum amount of data the writer will buffered
before flushing.
Defaults to 256 kB if unspecified. WS is the WriteSyncer around which BufferedWriteSyncer will buffer
writes.
This field is required. // closed when flushLoop has stopped // whether initialize() has run unexported fields for state // closed when flushLoop should stop // whether Stop() has runticker*time.Tickerwriter*bufio.Writer Stop closes the buffer, cleans up background goroutines, and flushes
remaining unwritten data. Sync flushes buffered log data into disk directly. Write writes log data into buffer syncer directly, multiple Write calls will be batched,
and log data will be flushed to disk when the buffer is full or periodically. flushLoop flushes the buffer at the configured interval until Stop is
called.(*BufferedWriteSyncer) initialize()
*BufferedWriteSyncer : WriteSyncer
*BufferedWriteSyncer : internal/bisect.Writer
*BufferedWriteSyncer : io.Writer
*BufferedWriteSyncer : crypto/tls.transcriptHash
A CallerEncoder serializes an EntryCaller to a primitive type. UnmarshalText unmarshals text to a CallerEncoder. "full" is unmarshaled to
FullCallerEncoder and anything else is unmarshaled to ShortCallerEncoder.
*CallerEncoder : encoding.TextUnmarshaler
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.EntryEntryEntry.CallerEntryCallerEntry.LevelLevelEntry.LoggerNamestringEntry.MessagestringEntry.StackstringEntry.Timetime.TimeErrorOutputWriteSyncerafterCheckWriteHookcores[]Core // best-effort detection of pool misuse 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. 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. 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. 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.(*CheckedEntry) reset()
func (*CheckedEntry).AddCore(ent Entry, core Core) *CheckedEntry
func (*CheckedEntry).After(ent Entry, hook CheckWriteHook) *CheckedEntry
func (*CheckedEntry).Should(ent Entry, should CheckWriteAction) *CheckedEntry
func Core.Check(Entry, *CheckedEntry) *CheckedEntry
func go.uber.org/zap.(*Logger).Check(lvl Level, msg string) *CheckedEntry
func getCheckedEntry() *CheckedEntry
func go.uber.org/zap.(*Logger).check(lvl Level, msg string) *CheckedEntry
func CheckWriteAction.OnWrite(ce *CheckedEntry, _ []Field)
func CheckWriteHook.OnWrite(*CheckedEntry, []Field)
func Core.Check(Entry, *CheckedEntry) *CheckedEntry
func putCheckedEntry(ce *CheckedEntry)
CheckWriteAction indicates what action to take after a log entry is
processed. Actions are ordered in increasing severity. OnWrite implements the OnWrite method to keep CheckWriteAction compatible
with the new CheckWriteHook interface which deprecates CheckWriteAction.
CheckWriteAction : CheckWriteHook
func (*CheckedEntry).Should(ent Entry, should CheckWriteAction) *CheckedEntry
func go.uber.org/zap.OnFatal(action CheckWriteAction) zap.Option
const WriteThenFatal
const WriteThenGoexit
const WriteThenNoop
const WriteThenPanic
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. OnWrite is invoked with the CheckedEntry that was written and a list
of fields added with that entry.
The list of fields DOES NOT include fields that were already added
to the logger with the With method.CheckWriteAction
func (*CheckedEntry).After(ent Entry, hook CheckWriteHook) *CheckedEntry
func go.uber.org/zap.WithFatalHook(hook CheckWriteHook) zap.Option
Clock is a source of time for logged entries. NewTicker returns *time.Ticker that holds a channel
that delivers "ticks" of a clock. Now returns the current local time.systemClock
Clock : github.com/cenkalti/backoff/v4.Clock
func go.uber.org/zap.WithClock(clock Clock) zap.Option
A DurationEncoder serializes a time.Duration to a primitive type. UnmarshalText unmarshals text to a DurationEncoder. "string" is unmarshaled
to StringDurationEncoder, and anything else is unmarshaled to
NanosDurationEncoder.
*DurationEncoder : encoding.TextUnmarshaler
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.( LevelEnabler) Enabled(Level) boolCore(interface)Level
go.uber.org/zap.AtomicLevel
go.uber.org/zap.LevelEnablerFunc
go.uber.org/zap/internal.LeveledEnabler(interface)hookedioCorelazyWithCoreleveledEnabler(interface)
*levelFilterCoremultiCorenopCoresampler
func LevelOf(enab LevelEnabler) Level
func NewCore(enc Encoder, ws WriteSyncer, enab LevelEnabler) Core
func NewIncreaseLevelCore(core Core, level LevelEnabler) (Core, error)
func go.uber.org/zap.AddStacktrace(lvl LevelEnabler) zap.Option
func go.uber.org/zap.IncreaseLevel(lvl LevelEnabler) zap.Option
A LevelEncoder serializes a Level to a primitive type. 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.
*LevelEncoder : encoding.TextUnmarshaler
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. Fields contains the entire encoded log context. cur is a pointer to the namespace we're currently writing to. AddArray implements ObjectEncoder. AddBinary implements ObjectEncoder. AddBool implements ObjectEncoder. AddByteString implements ObjectEncoder. AddComplex128 implements ObjectEncoder. AddComplex64 implements ObjectEncoder. AddDuration implements ObjectEncoder. AddFloat32 implements ObjectEncoder. AddFloat64 implements ObjectEncoder. AddInt implements ObjectEncoder. AddInt16 implements ObjectEncoder. AddInt32 implements ObjectEncoder. AddInt64 implements ObjectEncoder. AddInt8 implements ObjectEncoder. AddObject implements ObjectEncoder. AddReflected implements ObjectEncoder. AddString implements ObjectEncoder. AddTime implements ObjectEncoder. AddUint implements ObjectEncoder. AddUint16 implements ObjectEncoder. AddUint32 implements ObjectEncoder. AddUint64 implements ObjectEncoder. AddUint8 implements ObjectEncoder. AddUintptr implements ObjectEncoder. OpenNamespace implements ObjectEncoder.
*MapObjectEncoder : ObjectEncoder
func NewMapObjectEncoder() *MapObjectEncoder
A NameEncoder serializes a period-separated logger name to a primitive
type. UnmarshalText unmarshals text to a NameEncoder. Currently, everything is
unmarshaled to FullNameEncoder.
*NameEncoder : encoding.TextUnmarshaler
ObjectMarshalerFunc is a type adapter that turns a function into an
ObjectMarshaler. MarshalLogObject calls the underlying function.
ObjectMarshalerFunc : ObjectMarshaler[T]
ObjectMarshalerFunc : go.uber.org/zap.ObjectMarshalerPtr[...]
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. Encode encodes and writes to the underlying data stream.
*encoding/json.Encoder
func defaultReflectedEncoder(w io.Writer) ReflectedEncoder
SamplingDecision is a decision represented as a bit field made by sampler.
More decisions may be added in the future.
func nopSamplingHook(Entry, SamplingDecision)
const LogDropped
const LogSampled
A TimeEncoder serializes a time.Time to a primitive type. UnmarshalJSON unmarshals JSON to a TimeEncoder as same way UnmarshalYAML does. 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. 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
*TimeEncoder : encoding.TextUnmarshaler
*TimeEncoder : encoding/json.Unmarshaler
func TimeEncoderOfLayout(layout string) TimeEncoder
CoreCoreOncesync.Oncefields[]Field done indicates whether the action has been performed.
It is first in the struct because it is used in the hot path.
The hot path is inlined at every call site.
Placing done first allows more compact instructions on some architectures (amd64/386),
and fewer instructions (to calculate offset) on other architectures.Once.msync.Mutex(*lazyWithCore) Check(e Entry, ce *CheckedEntry) *CheckedEntry Do calls the function f if and only if Do is being called for the
first time for this instance of Once. In other words, given
var once Once
if once.Do(f) is called multiple times, only the first call will invoke f,
even if f has a different value in each invocation. A new instance of
Once is required for each function to execute.
Do is intended for initialization that must be run exactly once. Since f
is niladic, it may be necessary to use a function literal to capture the
arguments to a function to be invoked by Do:
config.once.Do(func() { config.init(filename) })
Because no call to Do returns until the one call to f returns, if f causes
Do to be called, it will deadlock.
If f panics, Do considers it to have returned; future calls of Do return
without calling f.( lazyWithCore) Enabled(Level) bool Sync flushes buffered logs (if any).(*lazyWithCore) With(fields []Field) Core 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.(*lazyWithCore) doSlow(f func())(*lazyWithCore) initOnce()
*lazyWithCore : Core
lazyWithCore : LevelEnabler
Mutexsync.MutexMutex.semauint32Mutex.stateint32wsWriteSyncer Lock locks m.
If the lock is already in use, the calling goroutine
blocks until the mutex is available.(*lockedWriteSyncer) Sync() error TryLock tries to lock m and reports whether it succeeded.
Note that while correct uses of TryLock do exist, they are rare,
and use of TryLock is often a sign of a deeper problem
in a particular use of mutexes. Unlock unlocks m.
It is a run-time error if m is not locked on entry to Unlock.
A locked Mutex is not associated with a particular goroutine.
It is allowed for one goroutine to lock a Mutex and then
arrange for another goroutine to unlock it.(*lockedWriteSyncer) Write(bs []byte) (int, error)(*lockedWriteSyncer) lockSlow()(*lockedWriteSyncer) unlockSlow(new int32)
*lockedWriteSyncer : WriteSyncer
*lockedWriteSyncer : internal/bisect.Writer
*lockedWriteSyncer : io.Writer
*lockedWriteSyncer : sync.Locker
*lockedWriteSyncer : crypto/tls.transcriptHash
( multiWriteSyncer) Sync() error See https://golang.org/src/io/multi.go
When not all underlying syncers write the same number of bytes,
the smallest number is returned even though Write() is called on
all of them.
multiWriteSyncer : WriteSyncer
multiWriteSyncer : internal/bisect.Writer
multiWriteSyncer : io.Writer
multiWriteSyncer : crypto/tls.transcriptHash
Package-Level Functions (total 53, in which 36 are exported)
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.
CapitalColorLevelEncoder serializes a Level to an all-caps string and adds color.
For example, InfoLevel is serialized to "INFO" and colored blue.
CapitalLevelEncoder serializes a Level to an all-caps string. For example,
InfoLevel is serialized to "INFO".
EpochMillisTimeEncoder serializes a time.Time to a floating-point number of
milliseconds since the Unix epoch.
EpochNanosTimeEncoder serializes a time.Time to an integer number of
nanoseconds since the Unix epoch.
EpochTimeEncoder serializes a time.Time to a floating-point number of seconds
since the Unix epoch.
FullCallerEncoder serializes a caller in /full/path/to/package/file:line
format.
FullNameEncoder serializes the logger name as-is.
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.
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)
}
Lock wraps a WriteSyncer in a mutex to make it safe for concurrent use. In
particular, *os.Files must be locked before use.
LowercaseColorLevelEncoder serializes a Level to a lowercase string and adds coloring.
For example, InfoLevel is serialized to "info" and colored blue.
LowercaseLevelEncoder serializes a Level to a lowercase string. For example,
InfoLevel is serialized to "info".
MillisDurationEncoder serializes a time.Duration to an integer number of
milliseconds elapsed.
NanosDurationEncoder serializes a time.Duration to an integer number of
nanoseconds elapsed.
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.
NewCore creates a Core that writes logs to a WriteSyncer.
NewEntryCaller makes an EntryCaller from the return signature of
runtime.Caller.
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.
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.
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).
NewMapObjectEncoder creates a new map-backed ObjectEncoder.
NewMultiWriteSyncer creates a WriteSyncer that duplicates its writes
and sync calls, much like io.MultiWriter.
NewNopCore returns a no-op 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.
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.
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.
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.
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.
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.
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.
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()
}
})
SecondsDurationEncoder serializes a time.Duration to a floating-point number of seconds elapsed.
ShortCallerEncoder serializes a caller in package/file:line format, trimming
all but the final directory from the full path.
StringDurationEncoder serializes a time.Duration using its built-in String
method.
TimeEncoderOfLayout returns TimeEncoder which serializes a time.Time using
given layout.
Encodes the given error into fields of an object. A field with the given
name is added for the error message.
If the error implements fmt.Formatter, a field with the name ${key}Verbose
is also added with the full verbose error message.
Finally, if the error implements errorGroup (from go.uber.org/multierr) or
causer (from github.com/pkg/errors), a ${key}Causes field is added with an
array of objects containing the errors this error was comprised of.
{
"error": err.Error(),
"errorVerbose": fmt.Sprintf("%+v", err),
"errorCauses": [
...
],
}
Type Parameters:
S: []byte | string safeAppendStringLike is a generic implementation of safeAddString and safeAddByteString.
It appends a string or byte slice to the buffer, escaping all special characters.
Package-Level Variables (total 11, in which 1 is exported)
DefaultClock is the default clock used by Zap in operations that require
time. This clock uses the system clock for all operations.
The pages are generated with Goldsv0.6.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.