// Copyright (c) 2016 Uber Technologies, Inc.1//2// Permission is hereby granted, free of charge, to any person obtaining a copy3// of this software and associated documentation files (the "Software"), to deal4// in the Software without restriction, including without limitation the rights5// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell6// copies of the Software, and to permit persons to whom the Software is7// furnished to do so, subject to the following conditions:8//9// The above copyright notice and this permission notice shall be included in10// all copies or substantial portions of the Software.11//12// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR13// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,14// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE15// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER16// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,17// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN18// THE SOFTWARE.1920package zap2122import (23"fmt"24"math"25"time"2627"go.uber.org/zap/internal/stacktrace"28"go.uber.org/zap/zapcore"29)3031// Field is an alias for Field. Aliasing this type dramatically32// improves the navigability of this package's API documentation.33type Field = zapcore.Field3435var (36_minTimeInt64 = time.Unix(0, math.MinInt64)37_maxTimeInt64 = time.Unix(0, math.MaxInt64)38)3940// Skip constructs a no-op field, which is often useful when handling invalid41// inputs in other Field constructors.42func Skip() Field {43return Field{Type: zapcore.SkipType}44}4546// nilField returns a field which will marshal explicitly as nil. See motivation47// in https://github.com/uber-go/zap/issues/753 . If we ever make breaking48// changes and add zapcore.NilType and zapcore.ObjectEncoder.AddNil, the49// implementation here should be changed to reflect that.50func nilField(key string) Field { return Reflect(key, nil) }5152// Binary constructs a field that carries an opaque binary blob.53//54// Binary data is serialized in an encoding-appropriate format. For example,55// zap's JSON encoder base64-encodes binary blobs. To log UTF-8 encoded text,56// use ByteString.57func Binary(key string, val []byte) Field {58return Field{Key: key, Type: zapcore.BinaryType, Interface: val}59}6061// Bool constructs a field that carries a bool.62func Bool(key string, val bool) Field {63var ival int6464if val {65ival = 166}67return Field{Key: key, Type: zapcore.BoolType, Integer: ival}68}6970// Boolp constructs a field that carries a *bool. The returned Field will safely71// and explicitly represent `nil` when appropriate.72func Boolp(key string, val *bool) Field {73if val == nil {74return nilField(key)75}76return Bool(key, *val)77}7879// ByteString constructs a field that carries UTF-8 encoded text as a []byte.80// To log opaque binary blobs (which aren't necessarily valid UTF-8), use81// Binary.82func ByteString(key string, val []byte) Field {83return Field{Key: key, Type: zapcore.ByteStringType, Interface: val}84}8586// Complex128 constructs a field that carries a complex number. Unlike most87// numeric fields, this costs an allocation (to convert the complex128 to88// interface{}).89func Complex128(key string, val complex128) Field {90return Field{Key: key, Type: zapcore.Complex128Type, Interface: val}91}9293// Complex128p constructs a field that carries a *complex128. The returned Field will safely94// and explicitly represent `nil` when appropriate.95func Complex128p(key string, val *complex128) Field {96if val == nil {97return nilField(key)98}99return Complex128(key, *val)100}101102// Complex64 constructs a field that carries a complex number. Unlike most103// numeric fields, this costs an allocation (to convert the complex64 to104// interface{}).105func Complex64(key string, val complex64) Field {106return Field{Key: key, Type: zapcore.Complex64Type, Interface: val}107}108109// Complex64p constructs a field that carries a *complex64. The returned Field will safely110// and explicitly represent `nil` when appropriate.111func Complex64p(key string, val *complex64) Field {112if val == nil {113return nilField(key)114}115return Complex64(key, *val)116}117118// Float64 constructs a field that carries a float64. The way the119// floating-point value is represented is encoder-dependent, so marshaling is120// necessarily lazy.121func Float64(key string, val float64) Field {122return Field{Key: key, Type: zapcore.Float64Type, Integer: int64(math.Float64bits(val))}123}124125// Float64p constructs a field that carries a *float64. The returned Field will safely126// and explicitly represent `nil` when appropriate.127func Float64p(key string, val *float64) Field {128if val == nil {129return nilField(key)130}131return Float64(key, *val)132}133134// Float32 constructs a field that carries a float32. The way the135// floating-point value is represented is encoder-dependent, so marshaling is136// necessarily lazy.137func Float32(key string, val float32) Field {138return Field{Key: key, Type: zapcore.Float32Type, Integer: int64(math.Float32bits(val))}139}140141// Float32p constructs a field that carries a *float32. The returned Field will safely142// and explicitly represent `nil` when appropriate.143func Float32p(key string, val *float32) Field {144if val == nil {145return nilField(key)146}147return Float32(key, *val)148}149150// Int constructs a field with the given key and value.151func Int(key string, val int) Field {152return Int64(key, int64(val))153}154155// Intp constructs a field that carries a *int. The returned Field will safely156// and explicitly represent `nil` when appropriate.157func Intp(key string, val *int) Field {158if val == nil {159return nilField(key)160}161return Int(key, *val)162}163164// Int64 constructs a field with the given key and value.165func Int64(key string, val int64) Field {166return Field{Key: key, Type: zapcore.Int64Type, Integer: val}167}168169// Int64p constructs a field that carries a *int64. The returned Field will safely170// and explicitly represent `nil` when appropriate.171func Int64p(key string, val *int64) Field {172if val == nil {173return nilField(key)174}175return Int64(key, *val)176}177178// Int32 constructs a field with the given key and value.179func Int32(key string, val int32) Field {180return Field{Key: key, Type: zapcore.Int32Type, Integer: int64(val)}181}182183// Int32p constructs a field that carries a *int32. The returned Field will safely184// and explicitly represent `nil` when appropriate.185func Int32p(key string, val *int32) Field {186if val == nil {187return nilField(key)188}189return Int32(key, *val)190}191192// Int16 constructs a field with the given key and value.193func Int16(key string, val int16) Field {194return Field{Key: key, Type: zapcore.Int16Type, Integer: int64(val)}195}196197// Int16p constructs a field that carries a *int16. The returned Field will safely198// and explicitly represent `nil` when appropriate.199func Int16p(key string, val *int16) Field {200if val == nil {201return nilField(key)202}203return Int16(key, *val)204}205206// Int8 constructs a field with the given key and value.207func Int8(key string, val int8) Field {208return Field{Key: key, Type: zapcore.Int8Type, Integer: int64(val)}209}210211// Int8p constructs a field that carries a *int8. The returned Field will safely212// and explicitly represent `nil` when appropriate.213func Int8p(key string, val *int8) Field {214if val == nil {215return nilField(key)216}217return Int8(key, *val)218}219220// String constructs a field with the given key and value.221func String(key string, val string) Field {222return Field{Key: key, Type: zapcore.StringType, String: val}223}224225// Stringp constructs a field that carries a *string. The returned Field will safely226// and explicitly represent `nil` when appropriate.227func Stringp(key string, val *string) Field {228if val == nil {229return nilField(key)230}231return String(key, *val)232}233234// Uint constructs a field with the given key and value.235func Uint(key string, val uint) Field {236return Uint64(key, uint64(val))237}238239// Uintp constructs a field that carries a *uint. The returned Field will safely240// and explicitly represent `nil` when appropriate.241func Uintp(key string, val *uint) Field {242if val == nil {243return nilField(key)244}245return Uint(key, *val)246}247248// Uint64 constructs a field with the given key and value.249func Uint64(key string, val uint64) Field {250return Field{Key: key, Type: zapcore.Uint64Type, Integer: int64(val)}251}252253// Uint64p constructs a field that carries a *uint64. The returned Field will safely254// and explicitly represent `nil` when appropriate.255func Uint64p(key string, val *uint64) Field {256if val == nil {257return nilField(key)258}259return Uint64(key, *val)260}261262// Uint32 constructs a field with the given key and value.263func Uint32(key string, val uint32) Field {264return Field{Key: key, Type: zapcore.Uint32Type, Integer: int64(val)}265}266267// Uint32p constructs a field that carries a *uint32. The returned Field will safely268// and explicitly represent `nil` when appropriate.269func Uint32p(key string, val *uint32) Field {270if val == nil {271return nilField(key)272}273return Uint32(key, *val)274}275276// Uint16 constructs a field with the given key and value.277func Uint16(key string, val uint16) Field {278return Field{Key: key, Type: zapcore.Uint16Type, Integer: int64(val)}279}280281// Uint16p constructs a field that carries a *uint16. The returned Field will safely282// and explicitly represent `nil` when appropriate.283func Uint16p(key string, val *uint16) Field {284if val == nil {285return nilField(key)286}287return Uint16(key, *val)288}289290// Uint8 constructs a field with the given key and value.291func Uint8(key string, val uint8) Field {292return Field{Key: key, Type: zapcore.Uint8Type, Integer: int64(val)}293}294295// Uint8p constructs a field that carries a *uint8. The returned Field will safely296// and explicitly represent `nil` when appropriate.297func Uint8p(key string, val *uint8) Field {298if val == nil {299return nilField(key)300}301return Uint8(key, *val)302}303304// Uintptr constructs a field with the given key and value.305func Uintptr(key string, val uintptr) Field {306return Field{Key: key, Type: zapcore.UintptrType, Integer: int64(val)}307}308309// Uintptrp constructs a field that carries a *uintptr. The returned Field will safely310// and explicitly represent `nil` when appropriate.311func Uintptrp(key string, val *uintptr) Field {312if val == nil {313return nilField(key)314}315return Uintptr(key, *val)316}317318// Reflect constructs a field with the given key and an arbitrary object. It uses319// an encoding-appropriate, reflection-based function to lazily serialize nearly320// any object into the logging context, but it's relatively slow and321// allocation-heavy. Outside tests, Any is always a better choice.322//323// If encoding fails (e.g., trying to serialize a map[int]string to JSON), Reflect324// includes the error message in the final log output.325func Reflect(key string, val interface{}) Field {326return Field{Key: key, Type: zapcore.ReflectType, Interface: val}327}328329// Namespace creates a named, isolated scope within the logger's context. All330// subsequent fields will be added to the new namespace.331//332// This helps prevent key collisions when injecting loggers into sub-components333// or third-party libraries.334func Namespace(key string) Field {335return Field{Key: key, Type: zapcore.NamespaceType}336}337338// Stringer constructs a field with the given key and the output of the value's339// String method. The Stringer's String method is called lazily.340func Stringer(key string, val fmt.Stringer) Field {341return Field{Key: key, Type: zapcore.StringerType, Interface: val}342}343344// Time constructs a Field with the given key and value. The encoder345// controls how the time is serialized.346func Time(key string, val time.Time) Field {347if val.Before(_minTimeInt64) || val.After(_maxTimeInt64) {348return Field{Key: key, Type: zapcore.TimeFullType, Interface: val}349}350return Field{Key: key, Type: zapcore.TimeType, Integer: val.UnixNano(), Interface: val.Location()}351}352353// Timep constructs a field that carries a *time.Time. The returned Field will safely354// and explicitly represent `nil` when appropriate.355func Timep(key string, val *time.Time) Field {356if val == nil {357return nilField(key)358}359return Time(key, *val)360}361362// Stack constructs a field that stores a stacktrace of the current goroutine363// under provided key. Keep in mind that taking a stacktrace is eager and364// expensive (relatively speaking); this function both makes an allocation and365// takes about two microseconds.366func Stack(key string) Field {367return StackSkip(key, 1) // skip Stack368}369370// StackSkip constructs a field similarly to Stack, but also skips the given371// number of frames from the top of the stacktrace.372func StackSkip(key string, skip int) Field {373// Returning the stacktrace as a string costs an allocation, but saves us374// from expanding the zapcore.Field union struct to include a byte slice. Since375// taking a stacktrace is already so expensive (~10us), the extra allocation376// is okay.377return String(key, stacktrace.Take(skip+1)) // skip StackSkip378}379380// Duration constructs a field with the given key and value. The encoder381// controls how the duration is serialized.382func Duration(key string, val time.Duration) Field {383return Field{Key: key, Type: zapcore.DurationType, Integer: int64(val)}384}385386// Durationp constructs a field that carries a *time.Duration. The returned Field will safely387// and explicitly represent `nil` when appropriate.388func Durationp(key string, val *time.Duration) Field {389if val == nil {390return nilField(key)391}392return Duration(key, *val)393}394395// Object constructs a field with the given key and ObjectMarshaler. It396// provides a flexible, but still type-safe and efficient, way to add map- or397// struct-like user-defined types to the logging context. The struct's398// MarshalLogObject method is called lazily.399func Object(key string, val zapcore.ObjectMarshaler) Field {400return Field{Key: key, Type: zapcore.ObjectMarshalerType, Interface: val}401}402403// Inline constructs a Field that is similar to Object, but it404// will add the elements of the provided ObjectMarshaler to the405// current namespace.406func Inline(val zapcore.ObjectMarshaler) Field {407return zapcore.Field{408Type: zapcore.InlineMarshalerType,409Interface: val,410}411}412413// Dict constructs a field containing the provided key-value pairs.414// It acts similar to [Object], but with the fields specified as arguments.415func Dict(key string, val ...Field) Field {416return dictField(key, val)417}418419// We need a function with the signature (string, T) for zap.Any.420func dictField(key string, val []Field) Field {421return Object(key, dictObject(val))422}423424type dictObject []Field425426func (d dictObject) MarshalLogObject(enc zapcore.ObjectEncoder) error {427for _, f := range d {428f.AddTo(enc)429}430return nil431}432433// We discovered an issue where zap.Any can cause a performance degradation434// when used in new goroutines.435//436// This happens because the compiler assigns 4.8kb (one zap.Field per arm of437// switch statement) of stack space for zap.Any when it takes the form:438//439// switch v := v.(type) {440// case string:441// return String(key, v)442// case int:443// return Int(key, v)444// // ...445// default:446// return Reflect(key, v)447// }448//449// To avoid this, we use the type switch to assign a value to a single local variable450// and then call a function on it.451// The local variable is just a function reference so it doesn't allocate452// when converted to an interface{}.453//454// A fair bit of experimentation went into this.455// See also:456//457// - https://github.com/uber-go/zap/pull/1301458// - https://github.com/uber-go/zap/pull/1303459// - https://github.com/uber-go/zap/pull/1304460// - https://github.com/uber-go/zap/pull/1305461// - https://github.com/uber-go/zap/pull/1308462//463// See https://github.com/golang/go/issues/62077 for upstream issue.464type anyFieldC[T any] func(string, T) Field465466func (f anyFieldC[T]) Any(key string, val any) Field {467v, _ := val.(T)468// val is guaranteed to be a T, except when it's nil.469return f(key, v)470}471472// Any takes a key and an arbitrary value and chooses the best way to represent473// them as a field, falling back to a reflection-based approach only if474// necessary.475//476// Since byte/uint8 and rune/int32 are aliases, Any can't differentiate between477// them. To minimize surprises, []byte values are treated as binary blobs, byte478// values are treated as uint8, and runes are always treated as integers.479func Any(key string, value interface{}) Field {480var c interface{ Any(string, any) Field }481482switch value.(type) {483case zapcore.ObjectMarshaler:484c = anyFieldC[zapcore.ObjectMarshaler](Object)485case zapcore.ArrayMarshaler:486c = anyFieldC[zapcore.ArrayMarshaler](Array)487case []Field:488c = anyFieldC[[]Field](dictField)489case bool:490c = anyFieldC[bool](Bool)491case *bool:492c = anyFieldC[*bool](Boolp)493case []bool:494c = anyFieldC[[]bool](Bools)495case complex128:496c = anyFieldC[complex128](Complex128)497case *complex128:498c = anyFieldC[*complex128](Complex128p)499case []complex128:500c = anyFieldC[[]complex128](Complex128s)501case complex64:502c = anyFieldC[complex64](Complex64)503case *complex64:504c = anyFieldC[*complex64](Complex64p)505case []complex64:506c = anyFieldC[[]complex64](Complex64s)507case float64:508c = anyFieldC[float64](Float64)509case *float64:510c = anyFieldC[*float64](Float64p)511case []float64:512c = anyFieldC[[]float64](Float64s)513case float32:514c = anyFieldC[float32](Float32)515case *float32:516c = anyFieldC[*float32](Float32p)517case []float32:518c = anyFieldC[[]float32](Float32s)519case int:520c = anyFieldC[int](Int)521case *int:522c = anyFieldC[*int](Intp)523case []int:524c = anyFieldC[[]int](Ints)525case int64:526c = anyFieldC[int64](Int64)527case *int64:528c = anyFieldC[*int64](Int64p)529case []int64:530c = anyFieldC[[]int64](Int64s)531case int32:532c = anyFieldC[int32](Int32)533case *int32:534c = anyFieldC[*int32](Int32p)535case []int32:536c = anyFieldC[[]int32](Int32s)537case int16:538c = anyFieldC[int16](Int16)539case *int16:540c = anyFieldC[*int16](Int16p)541case []int16:542c = anyFieldC[[]int16](Int16s)543case int8:544c = anyFieldC[int8](Int8)545case *int8:546c = anyFieldC[*int8](Int8p)547case []int8:548c = anyFieldC[[]int8](Int8s)549case string:550c = anyFieldC[string](String)551case *string:552c = anyFieldC[*string](Stringp)553case []string:554c = anyFieldC[[]string](Strings)555case uint:556c = anyFieldC[uint](Uint)557case *uint:558c = anyFieldC[*uint](Uintp)559case []uint:560c = anyFieldC[[]uint](Uints)561case uint64:562c = anyFieldC[uint64](Uint64)563case *uint64:564c = anyFieldC[*uint64](Uint64p)565case []uint64:566c = anyFieldC[[]uint64](Uint64s)567case uint32:568c = anyFieldC[uint32](Uint32)569case *uint32:570c = anyFieldC[*uint32](Uint32p)571case []uint32:572c = anyFieldC[[]uint32](Uint32s)573case uint16:574c = anyFieldC[uint16](Uint16)575case *uint16:576c = anyFieldC[*uint16](Uint16p)577case []uint16:578c = anyFieldC[[]uint16](Uint16s)579case uint8:580c = anyFieldC[uint8](Uint8)581case *uint8:582c = anyFieldC[*uint8](Uint8p)583case []byte:584c = anyFieldC[[]byte](Binary)585case uintptr:586c = anyFieldC[uintptr](Uintptr)587case *uintptr:588c = anyFieldC[*uintptr](Uintptrp)589case []uintptr:590c = anyFieldC[[]uintptr](Uintptrs)591case time.Time:592c = anyFieldC[time.Time](Time)593case *time.Time:594c = anyFieldC[*time.Time](Timep)595case []time.Time:596c = anyFieldC[[]time.Time](Times)597case time.Duration:598c = anyFieldC[time.Duration](Duration)599case *time.Duration:600c = anyFieldC[*time.Duration](Durationp)601case []time.Duration:602c = anyFieldC[[]time.Duration](Durations)603case error:604c = anyFieldC[error](NamedError)605case []error:606c = anyFieldC[[]error](Errors)607case fmt.Stringer:608c = anyFieldC[fmt.Stringer](Stringer)609default:610c = anyFieldC[any](Reflect)611}612613return c.Any(key, value)614}615616617