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. 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.
*BufferedWriteSyncer : WriteSyncer
*BufferedWriteSyncer : internal/bisect.Writer
*BufferedWriteSyncer : io.Writer
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.TimeErrorOutputWriteSyncer 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.
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 CheckWriteAction.OnWrite(ce *CheckedEntry, _ []Field)
func CheckWriteHook.OnWrite(*CheckedEntry, []Field)
func Core.Check(Entry, *CheckedEntry) *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.
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
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. Logging-specific marshalers. Built-in types. // for arbitrary bytes( Encoder) AddBool(key string, value bool) // for UTF-8 encoded bytes( Encoder) AddComplex128(key string, value complex128)( Encoder) AddComplex64(key string, value complex64)( Encoder) AddDuration(key string, value time.Duration)( Encoder) AddFloat32(key string, value float32)( Encoder) AddFloat64(key string, value float64)( Encoder) AddInt(key string, value int)( Encoder) AddInt16(key string, value int16)( Encoder) AddInt32(key string, value int32)( Encoder) AddInt64(key string, value int64)( Encoder) AddInt8(key string, value int8)( Encoder) AddObject(key string, marshaler ObjectMarshaler) error AddReflected uses reflection to serialize arbitrary objects, so it can be
slow and allocation-heavy.( Encoder) AddString(key, value string)( Encoder) AddTime(key string, value time.Time)( Encoder) AddUint(key string, value uint)( Encoder) AddUint16(key string, value uint16)( Encoder) AddUint32(key string, value uint32)( Encoder) AddUint64(key string, value uint64)( Encoder) AddUint8(key string, value uint8)( Encoder) AddUintptr(key string, value uintptr) Clone copies the encoder, ensuring that adding fields to the copy doesn't
affect the original. 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. 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.
Encoder : ObjectEncoder
func NewConsoleEncoder(cfg EncoderConfig) Encoder
func NewJSONEncoder(cfg EncoderConfig) Encoder
func Encoder.Clone() Encoder
func NewCore(enc Encoder, ws WriteSyncer, enab LevelEnabler) Core
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)
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. 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/gob.Encoder
*encoding/json.Encoder
*encoding/xml.Encoder
SamplingDecision is a decision represented as a bit field made by sampler.
More decisions may be added in the future.
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
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.( WriteSyncer) Sync() error( WriteSyncer) Write([]byte) (int, error)
*BufferedWriteSyncer
go.uber.org/zap.Sink(interface)
*github.com/hirochachacha/go-smb2.File
*github.com/pkg/sftp.File
*os.File
WriteSyncer : internal/bisect.Writer
WriteSyncer : io.Writer
func AddSync(w io.Writer) WriteSyncer
func Lock(ws WriteSyncer) WriteSyncer
func NewMultiWriteSyncer(ws ...WriteSyncer) WriteSyncer
func go.uber.org/zap.CombineWriteSyncers(writers ...WriteSyncer) WriteSyncer
func go.uber.org/zap.Open(paths ...string) (WriteSyncer, func(), error)
func Lock(ws WriteSyncer) WriteSyncer
func NewCore(enc Encoder, ws WriteSyncer, enab LevelEnabler) Core
func NewMultiWriteSyncer(ws ...WriteSyncer) WriteSyncer
func go.uber.org/zap.CombineWriteSyncers(writers ...WriteSyncer) WriteSyncer
func go.uber.org/zap.ErrorOutput(w WriteSyncer) zap.Option
Package-Level Functions (total 36)
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.
Package-Level Variables (only one)
DefaultClock is the default clock used by Zap in operations that require
time. This clock uses the system clock for all operations.
Package-Level Constants (total 45)
ArrayMarshalerType indicates that the field carries an ArrayMarshaler.
BinaryType indicates that the field carries an opaque binary blob.
BoolType indicates that the field carries a bool.
ByteStringType indicates that the field carries UTF-8 encoded bytes.
Complex128Type indicates that the field carries a complex128.
Complex64Type indicates that the field carries a complex128.
DebugLevel logs are typically voluminous, and are usually disabled in
production.
DefaultLineEnding defines the default line ending when writing logs.
Alternate line endings specified in EncoderConfig can override this
behavior.
DPanicLevel logs are particularly important errors. In development the
logger panics after writing the message.
DurationType indicates that the field carries a time.Duration.
ErrorLevel logs are high-priority. If an application is running smoothly,
it shouldn't generate any error-level logs.
ErrorType indicates that the field carries an error.
FatalLevel logs a message, then calls os.Exit(1).
Float32Type indicates that the field carries a float32.
Float64Type indicates that the field carries a float64.
InfoLevel is the default logging priority.
InlineMarshalerType indicates that the field carries an ObjectMarshaler
that should be inlined.
Int16Type indicates that the field carries an int16.
Int32Type indicates that the field carries an int32.
Int64Type indicates that the field carries an int64.
Int8Type indicates that the field carries an int8.
InvalidLevel is an invalid value for Level.
Core implementations may panic if they see messages of this level.
LogDropped indicates that the Sampler dropped a log entry.
LogSampled indicates that the Sampler sampled a log entry.
NamespaceType signals the beginning of an isolated namespace. All
subsequent fields should be added to the new namespace.
ObjectMarshalerType indicates that the field carries an ObjectMarshaler.
OmitKey defines the key to use when callers want to remove a key from log output.
PanicLevel logs a message, then panics.
ReflectType indicates that the field carries an interface{}, which should
be serialized using reflection.
SkipType indicates that the field is a no-op.
StringerType indicates that the field carries a fmt.Stringer.
StringType indicates that the field carries a string.
TimeFullType indicates that the field carries a time.Time stored as-is.
TimeType indicates that the field carries a time.Time that is
representable by a UnixNano() stored as an int64.
Uint16Type indicates that the field carries a uint16.
Uint32Type indicates that the field carries a uint32.
Uint64Type indicates that the field carries a uint64.
Uint8Type indicates that the field carries a uint8.
UintptrType indicates that the field carries a uintptr.
UnknownType is the default field type. Attempting to add it to an encoder will panic.
WarnLevel logs are more important than Info, but don't need individual
human review.
WriteThenFatal causes an os.Exit(1) after Write.
WriteThenGoexit runs runtime.Goexit after Write.
WriteThenNoop indicates that nothing special needs to be done. It's the
default behavior.
WriteThenPanic causes a panic after Write.
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.