encoding

package
v1.15.2 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2024 License: MIT Imports: 10 Imported by: 0

Documentation

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

This section is empty.

Functions

func AddFields

func AddFields(enc ObjectEncoder, fields []Field)

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 FullNameEncoder

func FullNameEncoder(loggerName string, enc PrimitiveArrayEncoder)

FullNameEncoder serializes the logger name as-is.

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 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 StringDurationEncoder

func StringDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder)

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

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 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([]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 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.
	EncodeTime     TimeEncoder     `json:"timeEncoder" yaml:"timeEncoder"`
	EncodeDuration DurationEncoder `json:"durationEncoder" yaml:"durationEncoder"`

	// 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 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 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 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

Jump to

Keyboard shortcuts

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