// 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 {400if val == nil {401return nilField(key)402}403return Field{Key: key, Type: zapcore.ObjectMarshalerType, Interface: val}404}405406// Inline constructs a Field that is similar to Object, but it407// will add the elements of the provided ObjectMarshaler to the408// current namespace.409func Inline(val zapcore.ObjectMarshaler) Field {410return zapcore.Field{411Type: zapcore.InlineMarshalerType,412Interface: val,413}414}415416// Dict constructs a field containing the provided key-value pairs.417// It acts similar to [Object], but with the fields specified as arguments.418func Dict(key string, val ...Field) Field {419return dictField(key, val)420}421422// We need a function with the signature (string, T) for zap.Any.423func dictField(key string, val []Field) Field {424return Object(key, dictObject(val))425}426427type dictObject []Field428429func (d dictObject) MarshalLogObject(enc zapcore.ObjectEncoder) error {430for _, f := range d {431f.AddTo(enc)432}433return nil434}435436// DictObject constructs a [zapcore.ObjectMarshaler] with the given list of fields.437// The resulting object marshaler can be used as input to [Object], [Objects], or438// any other functions that expect an object marshaler.439func DictObject(val ...Field) zapcore.ObjectMarshaler {440return dictObject(val)441}442443// We discovered an issue where zap.Any can cause a performance degradation444// when used in new goroutines.445//446// This happens because the compiler assigns 4.8kb (one zap.Field per arm of447// switch statement) of stack space for zap.Any when it takes the form:448//449// switch v := v.(type) {450// case string:451// return String(key, v)452// case int:453// return Int(key, v)454// // ...455// default:456// return Reflect(key, v)457// }458//459// To avoid this, we use the type switch to assign a value to a single local variable460// and then call a function on it.461// The local variable is just a function reference so it doesn't allocate462// when converted to an interface{}.463//464// A fair bit of experimentation went into this.465// See also:466//467// - https://github.com/uber-go/zap/pull/1301468// - https://github.com/uber-go/zap/pull/1303469// - https://github.com/uber-go/zap/pull/1304470// - https://github.com/uber-go/zap/pull/1305471// - https://github.com/uber-go/zap/pull/1308472//473// See https://github.com/golang/go/issues/62077 for upstream issue.474type anyFieldC[T any] func(string, T) Field475476func (f anyFieldC[T]) Any(key string, val any) Field {477v, _ := val.(T)478// val is guaranteed to be a T, except when it's nil.479return f(key, v)480}481482// Any takes a key and an arbitrary value and chooses the best way to represent483// them as a field, falling back to a reflection-based approach only if484// necessary.485//486// Since byte/uint8 and rune/int32 are aliases, Any can't differentiate between487// them. To minimize surprises, []byte values are treated as binary blobs, byte488// values are treated as uint8, and runes are always treated as integers.489func Any(key string, value interface{}) Field {490var c interface{ Any(string, any) Field }491492switch value.(type) {493case zapcore.ObjectMarshaler:494c = anyFieldC[zapcore.ObjectMarshaler](Object)495case zapcore.ArrayMarshaler:496c = anyFieldC[zapcore.ArrayMarshaler](Array)497case []Field:498c = anyFieldC[[]Field](dictField)499case bool:500c = anyFieldC[bool](Bool)501case *bool:502c = anyFieldC[*bool](Boolp)503case []bool:504c = anyFieldC[[]bool](Bools)505case complex128:506c = anyFieldC[complex128](Complex128)507case *complex128:508c = anyFieldC[*complex128](Complex128p)509case []complex128:510c = anyFieldC[[]complex128](Complex128s)511case complex64:512c = anyFieldC[complex64](Complex64)513case *complex64:514c = anyFieldC[*complex64](Complex64p)515case []complex64:516c = anyFieldC[[]complex64](Complex64s)517case float64:518c = anyFieldC[float64](Float64)519case *float64:520c = anyFieldC[*float64](Float64p)521case []float64:522c = anyFieldC[[]float64](Float64s)523case float32:524c = anyFieldC[float32](Float32)525case *float32:526c = anyFieldC[*float32](Float32p)527case []float32:528c = anyFieldC[[]float32](Float32s)529case int:530c = anyFieldC[int](Int)531case *int:532c = anyFieldC[*int](Intp)533case []int:534c = anyFieldC[[]int](Ints)535case int64:536c = anyFieldC[int64](Int64)537case *int64:538c = anyFieldC[*int64](Int64p)539case []int64:540c = anyFieldC[[]int64](Int64s)541case int32:542c = anyFieldC[int32](Int32)543case *int32:544c = anyFieldC[*int32](Int32p)545case []int32:546c = anyFieldC[[]int32](Int32s)547case int16:548c = anyFieldC[int16](Int16)549case *int16:550c = anyFieldC[*int16](Int16p)551case []int16:552c = anyFieldC[[]int16](Int16s)553case int8:554c = anyFieldC[int8](Int8)555case *int8:556c = anyFieldC[*int8](Int8p)557case []int8:558c = anyFieldC[[]int8](Int8s)559case string:560c = anyFieldC[string](String)561case *string:562c = anyFieldC[*string](Stringp)563case []string:564c = anyFieldC[[]string](Strings)565case uint:566c = anyFieldC[uint](Uint)567case *uint:568c = anyFieldC[*uint](Uintp)569case []uint:570c = anyFieldC[[]uint](Uints)571case uint64:572c = anyFieldC[uint64](Uint64)573case *uint64:574c = anyFieldC[*uint64](Uint64p)575case []uint64:576c = anyFieldC[[]uint64](Uint64s)577case uint32:578c = anyFieldC[uint32](Uint32)579case *uint32:580c = anyFieldC[*uint32](Uint32p)581case []uint32:582c = anyFieldC[[]uint32](Uint32s)583case uint16:584c = anyFieldC[uint16](Uint16)585case *uint16:586c = anyFieldC[*uint16](Uint16p)587case []uint16:588c = anyFieldC[[]uint16](Uint16s)589case uint8:590c = anyFieldC[uint8](Uint8)591case *uint8:592c = anyFieldC[*uint8](Uint8p)593case []byte:594c = anyFieldC[[]byte](Binary)595case uintptr:596c = anyFieldC[uintptr](Uintptr)597case *uintptr:598c = anyFieldC[*uintptr](Uintptrp)599case []uintptr:600c = anyFieldC[[]uintptr](Uintptrs)601case time.Time:602c = anyFieldC[time.Time](Time)603case *time.Time:604c = anyFieldC[*time.Time](Timep)605case []time.Time:606c = anyFieldC[[]time.Time](Times)607case time.Duration:608c = anyFieldC[time.Duration](Duration)609case *time.Duration:610c = anyFieldC[*time.Duration](Durationp)611case []time.Duration:612c = anyFieldC[[]time.Duration](Durations)613case error:614c = anyFieldC[error](NamedError)615case []error:616c = anyFieldC[[]error](Errors)617case fmt.Stringer:618c = anyFieldC[fmt.Stringer](Stringer)619default:620c = anyFieldC[any](Reflect)621}622623return c.Any(key, value)624}625626627