zapcore

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2020 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package zapcore defines and implements the low-level interfaces upon which zap is built. By providing alternate implementations of these interfaces, external packages can extend zap's capabilities.

Index

Constants

View Source
const DefaultLineEnding = "\n"

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

View Source
const OmitKey = ""

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

Variables

View Source
var Ordinary = "普通日志" + GetHost()
View Source
var Trace = "链路日志" + GetHost()

Functions

func CapitalColorLevelEncoder

func CapitalColorLevelEncoder(l Level, enc PrimitiveArrayEncoder)

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

func CapitalLevelEncoder

func CapitalLevelEncoder(l Level, enc PrimitiveArrayEncoder)

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

func EpochMillisTimeEncoder

func EpochMillisTimeEncoder(t time.Time, enc PrimitiveArrayEncoder)

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

func EpochNanosTimeEncoder

func EpochNanosTimeEncoder(t time.Time, enc PrimitiveArrayEncoder)

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

func EpochTimeEncoder

func EpochTimeEncoder(t time.Time, enc PrimitiveArrayEncoder)

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

func FullCallerEncoder

func FullCallerEncoder(caller EntryCaller, enc PrimitiveArrayEncoder)

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

func FullNameEncoder

func FullNameEncoder(loggerName string, enc PrimitiveArrayEncoder)

FullNameEncoder serializes the logger name as-is.

func GetHost

func GetHost() string

func ISO8601TimeEncoder

func ISO8601TimeEncoder(t time.Time, enc PrimitiveArrayEncoder)

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

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

func LowercaseColorLevelEncoder

func LowercaseColorLevelEncoder(l Level, enc PrimitiveArrayEncoder)

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

func LowercaseLevelEncoder

func LowercaseLevelEncoder(l Level, enc PrimitiveArrayEncoder)

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

func MillisDurationEncoder

func MillisDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder)

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

func NanosDurationEncoder

func NanosDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder)

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

func RFC3339NanoTimeEncoder

func RFC3339NanoTimeEncoder(t time.Time, enc PrimitiveArrayEncoder)

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

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

func RFC3339TimeEncoder

func RFC3339TimeEncoder(t time.Time, enc PrimitiveArrayEncoder)

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

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

func SecondsDurationEncoder

func SecondsDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder)

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

func ShortCallerEncoder

func ShortCallerEncoder(caller EntryCaller, enc PrimitiveArrayEncoder)

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

func StringDurationEncoder

func StringDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder)

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

func SyncEs

func SyncEs(text string, esClient *elastic.Client)

Types

type ArrayEncoder

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

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

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

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

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

type ArrayMarshaler

type ArrayMarshaler interface {
	MarshalLogArray(ArrayEncoder) error
}

ArrayMarshaler allows user-defined types to efficiently add themselves to the logging context, and to selectively omit information which shouldn't be included in logs (e.g., passwords).

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

type ArrayMarshalerFunc

type ArrayMarshalerFunc func(ArrayEncoder) error

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

func (ArrayMarshalerFunc) MarshalLogArray

func (f ArrayMarshalerFunc) MarshalLogArray(enc ArrayEncoder) error

MarshalLogArray calls the underlying function.

type CallerEncoder

type CallerEncoder func(EntryCaller, PrimitiveArrayEncoder)

A CallerEncoder serializes an EntryCaller to a primitive type.

func (*CallerEncoder) UnmarshalText

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

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

type CheckWriteAction

type CheckWriteAction uint8

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

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

type CheckedEntry

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

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

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

func (*CheckedEntry) AddCore

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

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

func (*CheckedEntry) Should

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

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

func (*CheckedEntry) Write

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

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

type Core

type Core interface {
	LevelEnabler

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

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

func NewCore

func NewCore(enc Encoder, ws WriteSyncer, enab LevelEnabler, es bool, esClient *elastic.Client) Core

NewCore creates a Core that writes logs to a WriteSyncer.

func NewIncreaseLevelCore

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

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

func NewNopCore

func NewNopCore() Core

NewNopCore returns a no-op Core.

func NewSampler deprecated

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

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

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

Keep in mind that 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

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.

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

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

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

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

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

type DurationEncoder

type DurationEncoder func(time.Duration, PrimitiveArrayEncoder)

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

func (*DurationEncoder) UnmarshalText

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

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

type Encoder

type Encoder interface {
	ObjectEncoder

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

	// EncodeEntry encodes an entry and fields, along with any accumulated
	// context, into a byte buffer and returns it. Any fields that are empty,
	// including fields on the `Entry` type, should be omitted.
	EncodeEntry(Entry, []Field) (*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

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

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

type EncoderConfig struct {
	// Set the keys used for each log entry. If any key is empty, that portion
	// of the entry is omitted.
	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"`
	LineEnding    string `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.
	EncodeLevel    LevelEncoder    `json:"levelEncoder" yaml:"levelEncoder"`
	EncodeTime     TimeEncoder     `json:"timeEncoder" yaml:"timeEncoder"`
	EncodeDuration DurationEncoder `json:"durationEncoder" yaml:"durationEncoder"`
	EncodeCaller   CallerEncoder   `json:"callerEncoder" yaml:"callerEncoder"`
	// Unlike the other primitive type encoders, EncodeName is optional. The
	// zero value falls back to FullNameEncoder.
	EncodeName NameEncoder `json:"nameEncoder" yaml:"nameEncoder"`
	// Configures the field separator used by the console encoder. Defaults
	// to tab.
	ConsoleSeparator string `json:"consoleSeparator" yaml:"consoleSeparator"`
}

An EncoderConfig allows users to configure the concrete encoders supplied by zapcore.

type Entry

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

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

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

type EntryCaller

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

EntryCaller represents the caller of a logging function.

func NewEntryCaller

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

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

func (EntryCaller) FullPath

func (ec EntryCaller) FullPath() string

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

func (EntryCaller) String

func (ec EntryCaller) String() string

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

func (EntryCaller) TrimmedPath

func (ec EntryCaller) TrimmedPath() string

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

type Field

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

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

func (Field) AddTo

func (f Field) AddTo(enc ObjectEncoder)

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

func (Field) Equals

func (f Field) Equals(other Field) bool

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

type FieldType

type FieldType uint8

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

const (
	// UnknownType is the default field type. Attempting to add it to an encoder will panic.
	UnknownType FieldType = iota
	// ArrayMarshalerType indicates that the field carries an ArrayMarshaler.
	ArrayMarshalerType
	// ObjectMarshalerType indicates that the field carries an ObjectMarshaler.
	ObjectMarshalerType
	// BinaryType indicates that the field carries an opaque binary blob.
	BinaryType
	// BoolType indicates that the field carries a bool.
	BoolType
	// ByteStringType indicates that the field carries UTF-8 encoded bytes.
	ByteStringType
	// Complex128Type indicates that the field carries a complex128.
	Complex128Type
	// Complex64Type indicates that the field carries a complex128.
	Complex64Type
	// DurationType indicates that the field carries a time.Duration.
	DurationType
	// Float64Type indicates that the field carries a float64.
	Float64Type
	// Float32Type indicates that the field carries a float32.
	Float32Type
	// Int64Type indicates that the field carries an int64.
	Int64Type
	// Int32Type indicates that the field carries an int32.
	Int32Type
	// Int16Type indicates that the field carries an int16.
	Int16Type
	// Int8Type indicates that the field carries an int8.
	Int8Type
	// StringType indicates that the field carries a string.
	StringType
	// TimeType indicates that the field carries a time.Time that is
	// representable by a UnixNano() stored as an int64.
	TimeType
	// TimeFullType indicates that the field carries a time.Time stored as-is.
	TimeFullType
	// Uint64Type indicates that the field carries 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
)

type Level

type Level int8

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

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

func (Level) CapitalString

func (l Level) CapitalString() string

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

func (Level) Enabled

func (l Level) Enabled(lvl Level) bool

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

func (*Level) Get

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

Get gets the level for the flag.Getter interface.

func (Level) MarshalText

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

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

func (*Level) Set

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

Set sets the level for the flag.Value interface.

func (Level) String

func (l Level) String() string

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

func (*Level) UnmarshalText

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

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

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

type LevelEnabler

type LevelEnabler interface {
	Enabled(Level) bool
}

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

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

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

type LevelEncoder

type LevelEncoder func(Level, PrimitiveArrayEncoder)

A LevelEncoder serializes a Level to a primitive type.

func (*LevelEncoder) UnmarshalText

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

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

type Log

type Log struct {
	Time       int64  `json:"time"`
	LogLevel   string `json:"log_level"`
	Src        string `json:"src"`
	ServerName string `json:"server_name"`
	Uid        int64  `json:"uid"`
	Tid        int64  `json:"tid"`
	Parent     int64  `json:"parent"`
	Data       string `json:"req_data"`
}

type MapObjectEncoder

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

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

func NewMapObjectEncoder

func NewMapObjectEncoder() *MapObjectEncoder

NewMapObjectEncoder creates a new map-backed ObjectEncoder.

func (*MapObjectEncoder) AddArray

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

AddArray implements ObjectEncoder.

func (*MapObjectEncoder) AddBinary

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

AddBinary implements ObjectEncoder.

func (*MapObjectEncoder) AddBool

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

AddBool implements ObjectEncoder.

func (*MapObjectEncoder) AddByteString

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

AddByteString implements ObjectEncoder.

func (*MapObjectEncoder) AddComplex128

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

AddComplex128 implements ObjectEncoder.

func (*MapObjectEncoder) AddComplex64

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

AddComplex64 implements ObjectEncoder.

func (MapObjectEncoder) AddDuration

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

AddDuration implements ObjectEncoder.

func (*MapObjectEncoder) AddFloat32

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

AddFloat32 implements ObjectEncoder.

func (*MapObjectEncoder) AddFloat64

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

AddFloat64 implements ObjectEncoder.

func (*MapObjectEncoder) AddInt

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

AddInt implements ObjectEncoder.

func (*MapObjectEncoder) AddInt16

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

AddInt16 implements ObjectEncoder.

func (*MapObjectEncoder) AddInt32

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

AddInt32 implements ObjectEncoder.

func (*MapObjectEncoder) AddInt64

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

AddInt64 implements ObjectEncoder.

func (*MapObjectEncoder) AddInt8

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

AddInt8 implements ObjectEncoder.

func (*MapObjectEncoder) AddObject

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

AddObject implements ObjectEncoder.

func (*MapObjectEncoder) AddReflected

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

AddReflected implements ObjectEncoder.

func (*MapObjectEncoder) AddString

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

AddString implements ObjectEncoder.

func (MapObjectEncoder) AddTime

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

AddTime implements ObjectEncoder.

func (*MapObjectEncoder) AddUint

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

AddUint implements ObjectEncoder.

func (*MapObjectEncoder) AddUint16

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

AddUint16 implements ObjectEncoder.

func (*MapObjectEncoder) AddUint32

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

AddUint32 implements ObjectEncoder.

func (*MapObjectEncoder) AddUint64

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

AddUint64 implements ObjectEncoder.

func (*MapObjectEncoder) AddUint8

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

AddUint8 implements ObjectEncoder.

func (*MapObjectEncoder) AddUintptr

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

AddUintptr implements ObjectEncoder.

func (*MapObjectEncoder) OpenNamespace

func (m *MapObjectEncoder) OpenNamespace(k string)

OpenNamespace implements ObjectEncoder.

type NameEncoder

type NameEncoder func(string, PrimitiveArrayEncoder)

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

func (*NameEncoder) UnmarshalText

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

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

type ObjectEncoder

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

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

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

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

type ObjectMarshaler

type ObjectMarshaler interface {
	MarshalLogObject(ObjectEncoder) error
}

ObjectMarshaler allows user-defined types to efficiently add themselves to the logging context, and to selectively omit information which shouldn't be included in logs (e.g., passwords).

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

type ObjectMarshalerFunc

type ObjectMarshalerFunc func(ObjectEncoder) error

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

func (ObjectMarshalerFunc) MarshalLogObject

func (f ObjectMarshalerFunc) MarshalLogObject(enc ObjectEncoder) error

MarshalLogObject calls the underlying function.

type PrimitiveArrayEncoder

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

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

type ReqData

type ReqData struct {
	Uid    int64 `json:"uid"`
	Tid    int64 `json:"tid"`
	Parent int64 `json:"parent"`
}

type SamplerOption

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

SamplerOption configures a Sampler.

func SamplerHook

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

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

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

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

type SamplingDecision

type SamplingDecision uint32

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

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

type TimeEncoder

type TimeEncoder func(time.Time, PrimitiveArrayEncoder)

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

func TimeEncoderOfLayout

func TimeEncoderOfLayout(layout string) TimeEncoder

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

func (*TimeEncoder) UnmarshalJSON

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

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

type WriteSyncer

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

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

func AddSync

func AddSync(w io.Writer) WriteSyncer

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

func Lock

func Lock(ws WriteSyncer) WriteSyncer

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

func NewMultiWriteSyncer

func NewMultiWriteSyncer(ws ...WriteSyncer) WriteSyncer

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

Jump to

Keyboard shortcuts

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