zapcore
packageThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
Documentation¶
Overview¶
Package zapcore defines and implements the low-level interfaces upon whichzap is built. By providing alternate implementations of these interfaces,external packages can extend zap's capabilities.
Index¶
- Constants
- Variables
- func CapitalColorLevelEncoder(l Level, enc PrimitiveArrayEncoder)
- func CapitalLevelEncoder(l Level, enc PrimitiveArrayEncoder)
- func EpochMillisTimeEncoder(t time.Time, enc PrimitiveArrayEncoder)
- func EpochNanosTimeEncoder(t time.Time, enc PrimitiveArrayEncoder)
- func EpochTimeEncoder(t time.Time, enc PrimitiveArrayEncoder)
- func FullCallerEncoder(caller EntryCaller, enc PrimitiveArrayEncoder)
- func FullNameEncoder(loggerName string, enc PrimitiveArrayEncoder)
- func ISO8601TimeEncoder(t time.Time, enc PrimitiveArrayEncoder)
- func LowercaseColorLevelEncoder(l Level, enc PrimitiveArrayEncoder)
- func LowercaseLevelEncoder(l Level, enc PrimitiveArrayEncoder)
- func MillisDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder)
- func NanosDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder)
- func RFC3339NanoTimeEncoder(t time.Time, enc PrimitiveArrayEncoder)
- func RFC3339TimeEncoder(t time.Time, enc PrimitiveArrayEncoder)
- func SecondsDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder)
- func ShortCallerEncoder(caller EntryCaller, enc PrimitiveArrayEncoder)
- func StringDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder)
- type ArrayEncoder
- type ArrayMarshaler
- type ArrayMarshalerFunc
- type BufferedWriteSyncer
- type CallerEncoder
- type CheckWriteAction
- type CheckWriteHook
- type CheckedEntry
- type Clock
- type Core
- func NewCore(enc Encoder, ws WriteSyncer, enab LevelEnabler) Core
- func NewIncreaseLevelCore(core Core, level LevelEnabler) (Core, error)
- func NewLazyWith(core Core, fields []Field) Core
- func NewNopCore() Core
- func NewSampler(core Core, tick time.Duration, first, thereafter int) Coredeprecated
- func NewSamplerWithOptions(core Core, tick time.Duration, first, thereafter int, opts ...SamplerOption) Core
- func NewTee(cores ...Core) Core
- func RegisterHooks(core Core, hooks ...func(Entry) error) Core
- type DurationEncoder
- type Encoder
- type EncoderConfig
- type Entry
- type EntryCaller
- type Field
- type FieldType
- type Level
- type LevelEnabler
- type LevelEncoder
- type MapObjectEncoder
- func (m *MapObjectEncoder) AddArray(key string, v ArrayMarshaler) error
- func (m *MapObjectEncoder) AddBinary(k string, v []byte)
- func (m *MapObjectEncoder) AddBool(k string, v bool)
- func (m *MapObjectEncoder) AddByteString(k string, v []byte)
- func (m *MapObjectEncoder) AddComplex128(k string, v complex128)
- func (m *MapObjectEncoder) AddComplex64(k string, v complex64)
- func (m MapObjectEncoder) AddDuration(k string, v time.Duration)
- func (m *MapObjectEncoder) AddFloat32(k string, v float32)
- func (m *MapObjectEncoder) AddFloat64(k string, v float64)
- func (m *MapObjectEncoder) AddInt(k string, v int)
- func (m *MapObjectEncoder) AddInt16(k string, v int16)
- func (m *MapObjectEncoder) AddInt32(k string, v int32)
- func (m *MapObjectEncoder) AddInt64(k string, v int64)
- func (m *MapObjectEncoder) AddInt8(k string, v int8)
- func (m *MapObjectEncoder) AddObject(k string, v ObjectMarshaler) error
- func (m *MapObjectEncoder) AddReflected(k string, v interface{}) error
- func (m *MapObjectEncoder) AddString(k string, v string)
- func (m MapObjectEncoder) AddTime(k string, v time.Time)
- func (m *MapObjectEncoder) AddUint(k string, v uint)
- func (m *MapObjectEncoder) AddUint16(k string, v uint16)
- func (m *MapObjectEncoder) AddUint32(k string, v uint32)
- func (m *MapObjectEncoder) AddUint64(k string, v uint64)
- func (m *MapObjectEncoder) AddUint8(k string, v uint8)
- func (m *MapObjectEncoder) AddUintptr(k string, v uintptr)
- func (m *MapObjectEncoder) OpenNamespace(k string)
- type NameEncoder
- type ObjectEncoder
- type ObjectMarshaler
- type ObjectMarshalerFunc
- type PrimitiveArrayEncoder
- type ReflectedEncoder
- type SamplerOption
- type SamplingDecision
- type TimeEncoder
- type WriteSyncer
Constants¶
const DefaultLineEnding = "\n"DefaultLineEnding defines the default line ending when writing logs.Alternate line endings specified in EncoderConfig can override thisbehavior.
const OmitKey = ""OmitKey defines the key to use when callers want to remove a key from log output.
Variables¶
var DefaultClock = systemClock{}DefaultClock is the default clock used by Zap in operations that requiretime. This clock uses the system clock for all operations.
Functions¶
funcCapitalColorLevelEncoder¶
func CapitalColorLevelEncoder(lLevel, encPrimitiveArrayEncoder)
CapitalColorLevelEncoder serializes a Level to an all-caps string and adds color.For example, InfoLevel is serialized to "INFO" and colored blue.
funcCapitalLevelEncoder¶
func CapitalLevelEncoder(lLevel, encPrimitiveArrayEncoder)
CapitalLevelEncoder serializes a Level to an all-caps string. For example,InfoLevel is serialized to "INFO".
funcEpochMillisTimeEncoder¶
func EpochMillisTimeEncoder(ttime.Time, encPrimitiveArrayEncoder)
EpochMillisTimeEncoder serializes a time.Time to a floating-point number ofmilliseconds since the Unix epoch.
funcEpochNanosTimeEncoder¶
func EpochNanosTimeEncoder(ttime.Time, encPrimitiveArrayEncoder)
EpochNanosTimeEncoder serializes a time.Time to an integer number ofnanoseconds since the Unix epoch.
funcEpochTimeEncoder¶
func EpochTimeEncoder(ttime.Time, encPrimitiveArrayEncoder)
EpochTimeEncoder serializes a time.Time to a floating-point number of secondssince the Unix epoch.
funcFullCallerEncoder¶
func FullCallerEncoder(callerEntryCaller, encPrimitiveArrayEncoder)
FullCallerEncoder serializes a caller in /full/path/to/package/file:lineformat.
funcFullNameEncoder¶added inv1.5.0
func FullNameEncoder(loggerNamestring, encPrimitiveArrayEncoder)
FullNameEncoder serializes the logger name as-is.
funcISO8601TimeEncoder¶
func ISO8601TimeEncoder(ttime.Time, encPrimitiveArrayEncoder)
ISO8601TimeEncoder serializes a time.Time to an ISO8601-formatted stringwith millisecond precision.
If enc supports AppendTimeLayout(t time.Time,layout string), it's usedinstead of appending a pre-formatted string value.
funcLowercaseColorLevelEncoder¶
func LowercaseColorLevelEncoder(lLevel, encPrimitiveArrayEncoder)
LowercaseColorLevelEncoder serializes a Level to a lowercase string and adds coloring.For example, InfoLevel is serialized to "info" and colored blue.
funcLowercaseLevelEncoder¶
func LowercaseLevelEncoder(lLevel, encPrimitiveArrayEncoder)
LowercaseLevelEncoder serializes a Level to a lowercase string. For example,InfoLevel is serialized to "info".
funcMillisDurationEncoder¶added inv1.14.0
func MillisDurationEncoder(dtime.Duration, encPrimitiveArrayEncoder)
MillisDurationEncoder serializes a time.Duration to an integer number ofmilliseconds elapsed.
funcNanosDurationEncoder¶
func NanosDurationEncoder(dtime.Duration, encPrimitiveArrayEncoder)
NanosDurationEncoder serializes a time.Duration to an integer number ofnanoseconds elapsed.
funcRFC3339NanoTimeEncoder¶added inv1.11.0
func RFC3339NanoTimeEncoder(ttime.Time, encPrimitiveArrayEncoder)
RFC3339NanoTimeEncoder serializes a time.Time to an RFC3339-formatted stringwith nanosecond precision.
If enc supports AppendTimeLayout(t time.Time,layout string), it's usedinstead of appending a pre-formatted string value.
funcRFC3339TimeEncoder¶added inv1.11.0
func RFC3339TimeEncoder(ttime.Time, encPrimitiveArrayEncoder)
RFC3339TimeEncoder serializes a time.Time to an RFC3339-formatted string.
If enc supports AppendTimeLayout(t time.Time,layout string), it's usedinstead of appending a pre-formatted string value.
funcSecondsDurationEncoder¶
func SecondsDurationEncoder(dtime.Duration, encPrimitiveArrayEncoder)
SecondsDurationEncoder serializes a time.Duration to a floating-point number of seconds elapsed.
funcShortCallerEncoder¶
func ShortCallerEncoder(callerEntryCaller, encPrimitiveArrayEncoder)
ShortCallerEncoder serializes a caller in package/file:line format, trimmingall but the final directory from the full path.
funcStringDurationEncoder¶
func StringDurationEncoder(dtime.Duration, encPrimitiveArrayEncoder)
StringDurationEncoder serializes a time.Duration using its built-in Stringmethod.
Types¶
typeArrayEncoder¶
type ArrayEncoder interface {// Built-in types.PrimitiveArrayEncoder// Time-related types.AppendDuration(time.Duration)AppendTime(time.Time)// Logging-specific marshalers.AppendArray(ArrayMarshaler)errorAppendObject(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 addingarray-like objects to the logging context. Of note, it supports mixed-typearrays even though they aren't typical in Go. Like slices, ArrayEncodersaren't safe for concurrent use (though typical use shouldn't require locks).
typeArrayMarshaler¶
type ArrayMarshaler interface {MarshalLogArray(ArrayEncoder)error}ArrayMarshaler allows user-defined types to efficiently add themselves to thelogging context, and to selectively omit information which shouldn't beincluded in logs (e.g., passwords).
Note: ArrayMarshaler is only used when zap.Array is used or whenpassed directly to zap.Any. It is not used when reflection-basedencoding is used.
typeArrayMarshalerFunc¶
type ArrayMarshalerFunc func(ArrayEncoder)error
ArrayMarshalerFunc is a type adapter that turns a function into anArrayMarshaler.
func (ArrayMarshalerFunc)MarshalLogArray¶
func (fArrayMarshalerFunc) MarshalLogArray(encArrayEncoder)error
MarshalLogArray calls the underlying function.
typeBufferedWriteSyncer¶added inv1.18.0
type BufferedWriteSyncer struct {// WS is the WriteSyncer around which BufferedWriteSyncer will buffer// writes.//// This field is required.WSWriteSyncer// Size specifies the maximum amount of data the writer will buffered// before flushing.//// Defaults to 256 kB if unspecified.Sizeint// FlushInterval specifies how often the writer should flush data if// there have been no writes.//// Defaults to 30 seconds if unspecified.FlushIntervaltime.Duration// Clock, if specified, provides control of the source of time for the// writer.//// Defaults to the system clock.ClockClock// contains filtered or unexported fields}A BufferedWriteSyncer is a WriteSyncer that buffers writes in-memory beforeflushing them to a wrapped WriteSyncer after reaching some limit, or at somefixed interval--whichever comes first.
BufferedWriteSyncer is safe for concurrent use. You don't need to usezapcore.Lock for WriteSyncers with BufferedWriteSyncer.
To set up a BufferedWriteSyncer, construct a WriteSyncer for your logdestination (*os.File is a valid WriteSyncer), wrap it withBufferedWriteSyncer, and defer a Stop() call for when you no longer need theobject.
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 FlushIntervalfields.For example, the following buffers up to 512 kB of logs before flushing themto 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()func (*BufferedWriteSyncer)Stop¶added inv1.18.0
func (s *BufferedWriteSyncer) Stop() (errerror)
Stop closes the buffer, cleans up background goroutines, and flushesremaining unwritten data.
func (*BufferedWriteSyncer)Sync¶added inv1.18.0
func (s *BufferedWriteSyncer) Sync()error
Sync flushes buffered log data into disk directly.
typeCallerEncoder¶
type CallerEncoder func(EntryCaller,PrimitiveArrayEncoder)
A CallerEncoder serializes an EntryCaller to a primitive type.
This function must make exactly one callto a PrimitiveArrayEncoder's Append* method.
func (*CallerEncoder)UnmarshalText¶
func (e *CallerEncoder) UnmarshalText(text []byte)error
UnmarshalText unmarshals text to a CallerEncoder. "full" is unmarshaled toFullCallerEncoder and anything else is unmarshaled to ShortCallerEncoder.
typeCheckWriteAction¶
type CheckWriteActionuint8
CheckWriteAction indicates what action to take after a log entry isprocessed. Actions are ordered in increasing severity.
const (// WriteThenNoop indicates that nothing special needs to be done. It's the// default behavior.WriteThenNoopCheckWriteAction =iota// WriteThenGoexit runs runtime.Goexit after Write.WriteThenGoexit// WriteThenPanic causes a panic after Write.WriteThenPanic// WriteThenFatal causes an os.Exit(1) after Write.WriteThenFatal)
func (CheckWriteAction)OnWrite¶added inv1.22.0
func (aCheckWriteAction) OnWrite(ce *CheckedEntry, _ []Field)
OnWrite implements the OnWrite method to keep CheckWriteAction compatiblewith the new CheckWriteHook interface which deprecates CheckWriteAction.
typeCheckWriteHook¶added inv1.22.0
type CheckWriteHook interface {// 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.OnWrite(*CheckedEntry, []Field)}CheckWriteHook is a custom action that may be executed after an entry iswritten.
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 withthe zap.WithFatalHook option.
typeCheckedEntry¶
type CheckedEntry struct {EntryErrorOutputWriteSyncer// contains filtered or unexported fields}CheckedEntry is an Entry together with a collection of Cores that havealready agreed to log it.
CheckedEntry references should be created by calling AddCore or After on anil *CheckedEntry. References are returned to a pool after Write, and MUSTNOT be retained after calling their Write method.
func (*CheckedEntry)AddCore¶
func (ce *CheckedEntry) AddCore(entEntry, coreCore) *CheckedEntry
AddCore adds a Core that has agreed to log this CheckedEntry. It's intended to beused by Core.Check implementations, and is safe to call on nil CheckedEntryreferences.
func (*CheckedEntry)After¶added inv1.22.0
func (ce *CheckedEntry) After(entEntry, hookCheckWriteHook) *CheckedEntry
After sets this CheckEntry's CheckWriteHook, which will be called after thislog entry has been written. It's safe to call this on nil CheckedEntryreferences.
func (*CheckedEntry)Shoulddeprecated
func (ce *CheckedEntry) Should(entEntry, shouldCheckWriteAction) *CheckedEntry
Should sets this CheckedEntry's CheckWriteAction, which controls whether aCore will panic or fatal after writing this log entry. Like AddCore, it'ssafe to call on nil CheckedEntry references.
Deprecated: UseCheckedEntry.After instead.
func (*CheckedEntry)Write¶
func (ce *CheckedEntry) Write(fields ...Field)
Write writes the entry to the stored Cores, returns any errors, and returnsthe CheckedEntry reference to a pool for immediate re-use. Finally, itexecutes any required CheckWriteAction.
typeClock¶added inv1.18.0
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.
typeCore¶
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 authorsto wrap in a more user-friendly API.
funcNewCore¶
func NewCore(encEncoder, wsWriteSyncer, enabLevelEnabler)Core
NewCore creates a Core that writes logs to a WriteSyncer.
funcNewIncreaseLevelCore¶added inv1.14.0
func NewIncreaseLevelCore(coreCore, levelLevelEnabler) (Core,error)
NewIncreaseLevelCore creates a core that can be used to increase the level ofan existing Core. It cannot be used to decrease the logging level, as it actsas a filter before calling the underlying core. If level decreases the log level,an error is returned.
funcNewLazyWith¶added inv1.26.0
NewLazyWith wraps a Core with a "lazy" Core that will only encode fields ifthe logger is written to (or is further chained in a lon-lazy manner).
funcNewSamplerdeprecated
NewSampler creates a Core that samples incoming entries, whichcaps the CPU and I/O load of logging while attempting to preserve arepresentative subset of your logs.
Zap samples by logging the first N entries with a given level and messageeach tick. If more Entries with the same level and message are seen duringthe same interval, every Mth message is logged and the rest are dropped.
Keep in mind that zap's sampling implementation is optimized for speed overabsolute precision; under load, each tick may be slightly over- orunder-sampled.
Deprecated: use NewSamplerWithOptions.
funcNewSamplerWithOptions¶added inv1.15.0
func NewSamplerWithOptions(coreCore, ticktime.Duration, first, thereafterint, opts ...SamplerOption)Core
NewSamplerWithOptions creates a Core that samples incoming entries, whichcaps the CPU and I/O load of logging while attempting to preserve arepresentative subset of your logs.
Zap samples by logging the first N entries with a given level and messageeach tick. If more Entries with the same level and message are seen duringthe 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 messagein a one second interval as-is. Following that, it will allow throughevery 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 Nin that interval.
Sampler can be configured to report sampling decisions with the SamplerHookoption.
Keep in mind that Zap's sampling implementation is optimized for speed overabsolute precision; under load, each tick may be slightly over- orunder-sampled.
funcNewTee¶
NewTee creates a Core that duplicates log entries into two or moreunderlying Cores.
Calling it with a single Core returns the input unchanged, and callingit with no input returns a no-op Core.
funcRegisterHooks¶
RegisterHooks wraps a Core and runs a collection of user-defined callbackhooks each time a message is logged. Execution of the callbacks is blocking.
This offers users an easy way to register simple callbacks (e.g., metricscollection) without implementing the full Core interface.
typeDurationEncoder¶
type DurationEncoder func(time.Duration,PrimitiveArrayEncoder)
A DurationEncoder serializes a time.Duration to a primitive type.
This function must make exactly one callto a PrimitiveArrayEncoder's Append* method.
func (*DurationEncoder)UnmarshalText¶
func (e *DurationEncoder) UnmarshalText(text []byte)error
UnmarshalText unmarshals text to a DurationEncoder. "string" is unmarshaledto StringDurationEncoder, and anything else is unmarshaled toNanosDurationEncoder.
typeEncoder¶
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) (*buffer.Buffer,error)}Encoder is a format-agnostic interface for all log entry marshalers. Sincelog encoders don't need to support the same wide range of use cases asgeneral-purpose marshalers, it's possible to make them faster andlower-allocation.
Implementations of the ObjectEncoder interface's methods can, of course,freely modify the receiver. However, the Clone and EncodeEntry methods willbe called concurrently and shouldn't modify the receiver.
funcNewConsoleEncoder¶
func NewConsoleEncoder(cfgEncoderConfig)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 thestructured context as JSON.
Note that although the console encoder doesn't use the keys specified in theencoder configuration, it will omit any element whose key is set to the emptystring.
funcNewJSONEncoder¶
func NewJSONEncoder(cfgEncoderConfig)Encoder
NewJSONEncoder creates a fast, low-allocation JSON encoder. The encoderappropriately escapes all field keys and values.
Note that the encoder doesn't deduplicate keys, so it's possible to producea message like
{"foo":"bar","foo":"baz"}This is permitted by the JSON specification, but not encouraged. Manylibraries will ignore duplicate key-value pairs (typically keeping the lastpair) when unmarshaling, but users should attempt to avoid adding duplicatekeys.
typeEncoderConfig¶
type EncoderConfig struct {// Set the keys used for each log entry. If any key is empty, that portion// of the entry is omitted.MessageKeystring `json:"messageKey" yaml:"messageKey"`LevelKeystring `json:"levelKey" yaml:"levelKey"`TimeKeystring `json:"timeKey" yaml:"timeKey"`NameKeystring `json:"nameKey" yaml:"nameKey"`CallerKeystring `json:"callerKey" yaml:"callerKey"`FunctionKeystring `json:"functionKey" yaml:"functionKey"`StacktraceKeystring `json:"stacktraceKey" yaml:"stacktraceKey"`SkipLineEndingbool `json:"skipLineEnding" yaml:"skipLineEnding"`LineEndingstring `json:"lineEnding" yaml:"lineEnding"`// 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.EncodeLevelLevelEncoder `json:"levelEncoder" yaml:"levelEncoder"`EncodeTimeTimeEncoder `json:"timeEncoder" yaml:"timeEncoder"`EncodeDurationDurationEncoder `json:"durationEncoder" yaml:"durationEncoder"`EncodeCallerCallerEncoder `json:"callerEncoder" yaml:"callerEncoder"`// Unlike the other primitive type encoders, EncodeName is optional. The// zero value falls back to FullNameEncoder.EncodeNameNameEncoder `json:"nameEncoder" yaml:"nameEncoder"`// Configure the encoder for interface{} type objects.// If not provided, objects are encoded using json.EncoderNewReflectedEncoder func(io.Writer)ReflectedEncoder `json:"-" yaml:"-"`// Configures the field separator used by the console encoder. Defaults// to tab.ConsoleSeparatorstring `json:"consoleSeparator" yaml:"consoleSeparator"`}An EncoderConfig allows users to configure the concrete encoders supplied byzapcore.
typeEntry¶
type Entry struct {LevelLevelTimetime.TimeLoggerNamestringMessagestringCallerEntryCallerStackstring}An Entry represents a complete log message. The entry's structured contextis already serialized, but the log level, time, message, and call siteinformation are available for inspection and modification. Any fields leftempty will be omitted when encoding.
Entries are pooled, so any functions that accept them MUST be careful not toretain references to them.
typeEntryCaller¶
EntryCaller represents the caller of a logging function.
funcNewEntryCaller¶
func NewEntryCaller(pcuintptr, filestring, lineint, okbool)EntryCaller
NewEntryCaller makes an EntryCaller from the return signature ofruntime.Caller.
func (EntryCaller)FullPath¶
func (ecEntryCaller) FullPath()string
FullPath returns a /full/path/to/package/file:line description of thecaller.
func (EntryCaller)String¶
func (ecEntryCaller) String()string
String returns the full path and line number of the caller.
func (EntryCaller)TrimmedPath¶
func (ecEntryCaller) TrimmedPath()string
TrimmedPath returns a package/file:line description of the caller,preserving only the leaf directory name and file name.
typeField¶
A Field is a marshaling operation used to add a key-value pair to a logger'scontext. Most fields are lazily marshaled, so it's inexpensive to add fieldsto disabled debug-level log statements.
func (Field)AddTo¶
func (fField) AddTo(encObjectEncoder)
AddTo exports a field through the ObjectEncoder interface. It's primarilyuseful to library authors, and shouldn't be necessary in most applications.
typeFieldType¶
type FieldTypeuint8
A FieldType indicates which member of the Field union struct should be usedand how it should be serialized.
const (// UnknownType is the default field type. Attempting to add it to an encoder will panic.UnknownTypeFieldType =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 complex64.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 a uint64.Uint64Type// Uint32Type indicates that the field carries a uint32.Uint32Type// Uint16Type indicates that the field carries a uint16.Uint16Type// Uint8Type indicates that the field carries a uint8.Uint8Type// UintptrType indicates that the field carries a 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)
typeLevel¶
type Levelint8
A Level is a logging priority. Higher levels are more important.
const (// DebugLevel logs are typically voluminous, and are usually disabled in// production.DebugLevelLevel =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// InvalidLevel is an invalid value for Level.//// Core implementations may panic if they see messages of this level.InvalidLevel = _maxLevel + 1)
funcLevelOf¶added inv1.23.0
func LevelOf(enabLevelEnabler)Level
LevelOf reports the minimum enabled log level for the given LevelEnablerfrom Zap's supported log levels, orInvalidLevel if none of them areenabled.
A LevelEnabler may implement a 'Level() Level' method to override thebehavior of this function.
func (c *core) Level() Level {return c.currentLevel}It is recommended thatCore implementations that wrap other cores useLevelOf to retrieve the level of the wrapped core. For example,
func (c *coreWrapper) Level() Level {return zapcore.LevelOf(c.wrappedCore)}funcParseLevel¶added inv1.21.0
ParseLevel parses a level based on the lower-case or all-caps ASCIIrepresentation of the log level. If the provided ASCII representation isinvalid an error is returned.
This is particularly useful when dealing with text input to configure loglevels.
func (Level)CapitalString¶
CapitalString returns an all-caps ASCII representation of the log level.
func (Level)MarshalText¶
MarshalText marshals the Level to text. Note that the text representationdrops the -Level suffix (see example).
func (*Level)UnmarshalText¶
UnmarshalText unmarshals text to a level. Like MarshalText, UnmarshalTextexpects the text representation of a Level to drop the -Level suffix (seeexample).
In particular, this makes it easy to configure logging levels using YAML,TOML, or JSON files.
typeLevelEnabler¶
LevelEnabler decides whether a given logging level is enabled when logging amessage.
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 returnstrue for itself and all higher logging levels. For example WarnLevel.Enabled()will return true for WarnLevel, ErrorLevel, DPanicLevel, PanicLevel, andFatalLevel, but return false for InfoLevel and DebugLevel.
typeLevelEncoder¶
type LevelEncoder func(Level,PrimitiveArrayEncoder)
A LevelEncoder serializes a Level to a primitive type.
This function must make exactly one callto a PrimitiveArrayEncoder's Append* method.
func (*LevelEncoder)UnmarshalText¶
func (e *LevelEncoder) UnmarshalText(text []byte)error
UnmarshalText unmarshals text to a LevelEncoder. "capital" is unmarshaled toCapitalLevelEncoder, "coloredCapital" is unmarshaled to CapitalColorLevelEncoder,"colored" is unmarshaled to LowercaseColorLevelEncoder, and anything elseis unmarshaled to LowercaseLevelEncoder.
typeMapObjectEncoder¶
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 simplemap[string]interface{}. It's not fast enough for production use, but it'shelpful in tests.
funcNewMapObjectEncoder¶
func NewMapObjectEncoder() *MapObjectEncoder
NewMapObjectEncoder creates a new map-backed ObjectEncoder.
func (*MapObjectEncoder)AddArray¶
func (m *MapObjectEncoder) AddArray(keystring, vArrayMarshaler)error
AddArray implements ObjectEncoder.
func (*MapObjectEncoder)AddBinary¶
func (m *MapObjectEncoder) AddBinary(kstring, v []byte)
AddBinary implements ObjectEncoder.
func (*MapObjectEncoder)AddBool¶
func (m *MapObjectEncoder) AddBool(kstring, vbool)
AddBool implements ObjectEncoder.
func (*MapObjectEncoder)AddByteString¶
func (m *MapObjectEncoder) AddByteString(kstring, v []byte)
AddByteString implements ObjectEncoder.
func (*MapObjectEncoder)AddComplex128¶
func (m *MapObjectEncoder) AddComplex128(kstring, vcomplex128)
AddComplex128 implements ObjectEncoder.
func (*MapObjectEncoder)AddComplex64¶
func (m *MapObjectEncoder) AddComplex64(kstring, vcomplex64)
AddComplex64 implements ObjectEncoder.
func (MapObjectEncoder)AddDuration¶
func (mMapObjectEncoder) AddDuration(kstring, vtime.Duration)
AddDuration implements ObjectEncoder.
func (*MapObjectEncoder)AddFloat32¶
func (m *MapObjectEncoder) AddFloat32(kstring, vfloat32)
AddFloat32 implements ObjectEncoder.
func (*MapObjectEncoder)AddFloat64¶
func (m *MapObjectEncoder) AddFloat64(kstring, vfloat64)
AddFloat64 implements ObjectEncoder.
func (*MapObjectEncoder)AddInt¶
func (m *MapObjectEncoder) AddInt(kstring, vint)
AddInt implements ObjectEncoder.
func (*MapObjectEncoder)AddInt16¶
func (m *MapObjectEncoder) AddInt16(kstring, vint16)
AddInt16 implements ObjectEncoder.
func (*MapObjectEncoder)AddInt32¶
func (m *MapObjectEncoder) AddInt32(kstring, vint32)
AddInt32 implements ObjectEncoder.
func (*MapObjectEncoder)AddInt64¶
func (m *MapObjectEncoder) AddInt64(kstring, vint64)
AddInt64 implements ObjectEncoder.
func (*MapObjectEncoder)AddInt8¶
func (m *MapObjectEncoder) AddInt8(kstring, vint8)
AddInt8 implements ObjectEncoder.
func (*MapObjectEncoder)AddObject¶
func (m *MapObjectEncoder) AddObject(kstring, vObjectMarshaler)error
AddObject implements ObjectEncoder.
func (*MapObjectEncoder)AddReflected¶
func (m *MapObjectEncoder) AddReflected(kstring, v interface{})error
AddReflected implements ObjectEncoder.
func (*MapObjectEncoder)AddString¶
func (m *MapObjectEncoder) AddString(kstring, vstring)
AddString implements ObjectEncoder.
func (MapObjectEncoder)AddTime¶
func (mMapObjectEncoder) AddTime(kstring, vtime.Time)
AddTime implements ObjectEncoder.
func (*MapObjectEncoder)AddUint¶
func (m *MapObjectEncoder) AddUint(kstring, vuint)
AddUint implements ObjectEncoder.
func (*MapObjectEncoder)AddUint16¶
func (m *MapObjectEncoder) AddUint16(kstring, vuint16)
AddUint16 implements ObjectEncoder.
func (*MapObjectEncoder)AddUint32¶
func (m *MapObjectEncoder) AddUint32(kstring, vuint32)
AddUint32 implements ObjectEncoder.
func (*MapObjectEncoder)AddUint64¶
func (m *MapObjectEncoder) AddUint64(kstring, vuint64)
AddUint64 implements ObjectEncoder.
func (*MapObjectEncoder)AddUint8¶
func (m *MapObjectEncoder) AddUint8(kstring, vuint8)
AddUint8 implements ObjectEncoder.
func (*MapObjectEncoder)AddUintptr¶
func (m *MapObjectEncoder) AddUintptr(kstring, vuintptr)
AddUintptr implements ObjectEncoder.
func (*MapObjectEncoder)OpenNamespace¶
func (m *MapObjectEncoder) OpenNamespace(kstring)
OpenNamespace implements ObjectEncoder.
typeNameEncoder¶added inv1.5.0
type NameEncoder func(string,PrimitiveArrayEncoder)
A NameEncoder serializes a period-separated logger name to a primitivetype.
This function must make exactly one callto a PrimitiveArrayEncoder's Append* method.
func (*NameEncoder)UnmarshalText¶added inv1.5.0
func (e *NameEncoder) UnmarshalText(text []byte)error
UnmarshalText unmarshals text to a NameEncoder. Currently, everything isunmarshaled to FullNameEncoder.
typeObjectEncoder¶
type ObjectEncoder interface {// Logging-specific marshalers.AddArray(keystring, marshalerArrayMarshaler)errorAddObject(keystring, marshalerObjectMarshaler)error// Built-in types.AddBinary(keystring, value []byte)// for arbitrary bytesAddByteString(keystring, value []byte)// for UTF-8 encoded bytesAddBool(keystring, valuebool)AddComplex128(keystring, valuecomplex128)AddComplex64(keystring, valuecomplex64)AddDuration(keystring, valuetime.Duration)AddFloat64(keystring, valuefloat64)AddFloat32(keystring, valuefloat32)AddInt(keystring, valueint)AddInt64(keystring, valueint64)AddInt32(keystring, valueint32)AddInt16(keystring, valueint16)AddInt8(keystring, valueint8)AddString(key, valuestring)AddTime(keystring, valuetime.Time)AddUint(keystring, valueuint)AddUint64(keystring, valueuint64)AddUint32(keystring, valueuint32)AddUint16(keystring, valueuint16)AddUint8(keystring, valueuint8)AddUintptr(keystring, valueuintptr)// AddReflected uses reflection to serialize arbitrary objects, so it can be// slow and allocation-heavy.AddReflected(keystring, 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(keystring)}ObjectEncoder is a strongly-typed, encoding-agnostic interface for adding amap- or struct-like object to the logging context. Like maps, ObjectEncodersaren't safe for concurrent use (though typical use shouldn't require locks).
typeObjectMarshaler¶
type ObjectMarshaler interface {MarshalLogObject(ObjectEncoder)error}ObjectMarshaler allows user-defined types to efficiently add themselves to thelogging context, and to selectively omit information which shouldn't beincluded in logs (e.g., passwords).
Note: ObjectMarshaler is only used when zap.Object is used or whenpassed directly to zap.Any. It is not used when reflection-basedencoding is used.
typeObjectMarshalerFunc¶
type ObjectMarshalerFunc func(ObjectEncoder)error
ObjectMarshalerFunc is a type adapter that turns a function into anObjectMarshaler.
func (ObjectMarshalerFunc)MarshalLogObject¶
func (fObjectMarshalerFunc) MarshalLogObject(encObjectEncoder)error
MarshalLogObject calls the underlying function.
typePrimitiveArrayEncoder¶
type PrimitiveArrayEncoder interface {// Built-in types.AppendBool(bool)AppendByteString([]byte)// for UTF-8 encoded bytesAppendComplex128(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 dealsonly in Go's built-in types. It's included only so that Duration- andTimeEncoders cannot trigger infinite recursion.
typeReflectedEncoder¶added inv1.20.0
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'sJSON encoder. These have the ReflectType field type.Use EncoderConfig.NewReflectedEncoder to set this.
typeSamplerOption¶added inv1.15.0
type SamplerOption interface {// contains filtered or unexported methods}SamplerOption configures a Sampler.
funcSamplerHook¶added inv1.15.0
func SamplerHook(hook func(entryEntry, decSamplingDecision))SamplerOption
SamplerHook registers a function which will be called when Sampler makes adecision.
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.Int64zapcore.SamplerHook(func(ent zapcore.Entry, dec zapcore.SamplingDecision) { if dec&zapcore.LogDropped > 0 { dropped.Inc() }})typeSamplingDecision¶added inv1.15.0
type SamplingDecisionuint32
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.LogDroppedSamplingDecision = 1 <<iota// LogSampled indicates that the Sampler sampled a log entry.LogSampled)
typeTimeEncoder¶
type TimeEncoder func(time.Time,PrimitiveArrayEncoder)
A TimeEncoder serializes a time.Time to a primitive type.
This function must make exactly one callto a PrimitiveArrayEncoder's Append* method.
funcTimeEncoderOfLayout¶added inv1.16.0
func TimeEncoderOfLayout(layoutstring)TimeEncoder
TimeEncoderOfLayout returns TimeEncoder which serializes a time.Time usinggiven layout.
func (*TimeEncoder)UnmarshalJSON¶added inv1.16.0
func (e *TimeEncoder) UnmarshalJSON(data []byte)error
UnmarshalJSON unmarshals JSON to a TimeEncoder as same way UnmarshalYAML does.
func (*TimeEncoder)UnmarshalText¶
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 (*TimeEncoder)UnmarshalYAML¶added inv1.16.0
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
typeWriteSyncer¶
A WriteSyncer is an io.Writer that can also flush any buffered data. Notethat *os.File (and thus, os.Stderr and os.Stdout) implement WriteSyncer.
funcAddSync¶
func AddSync(wio.Writer)WriteSyncer
AddSync converts an io.Writer to a WriteSyncer. It attempts to beintelligent: 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.
funcLock¶
func Lock(wsWriteSyncer)WriteSyncer
Lock wraps a WriteSyncer in a mutex to make it safe for concurrent use. Inparticular, *os.Files must be locked before use.
funcNewMultiWriteSyncer¶
func NewMultiWriteSyncer(ws ...WriteSyncer)WriteSyncer
NewMultiWriteSyncer creates a WriteSyncer that duplicates its writesand sync calls, much like io.MultiWriter.