Zap uses strongly-typed fields to avoid reflection and allocations during logging. Each field constructor creates a Field value that efficiently encodes typed data.
type Field = zapcore.FieldFields are the core unit of structured logging context in zap. All Logger methods accept variadic Field arguments.
func String(key string, val string) Field
func Stringp(key string, val *string) Fieldfunc Int(key string, val int) Field
func Int8(key string, val int8) Field
func Int16(key string, val int16) Field
func Int32(key string, val int32) Field
func Int64(key string, val int64) Field
func Intp(key string, val *int) Field
func Int8p(key string, val *int8) Field
func Int16p(key string, val *int16) Field
func Int32p(key string, val *int32) Field
func Int64p(key string, val *int64) FieldSigned integer fields and their pointer variants.
func Uint(key string, val uint) Field
func Uint8(key string, val uint8) Field
func Uint16(key string, val uint16) Field
func Uint32(key string, val uint32) Field
func Uint64(key string, val uint64) Field
func Uintptr(key string, val uintptr) Field
func Uintp(key string, val *uint) Field
func Uint8p(key string, val *uint8) Field
func Uint16p(key string, val *uint16) Field
func Uint32p(key string, val *uint32) Field
func Uint64p(key string, val *uint64) Field
func Uintptrp(key string, val *uintptr) FieldUnsigned integer fields and their pointer variants.
func Bool(key string, val bool) Field
func Boolp(key string, val *bool) FieldBoolean field and pointer variant.
func Float32(key string, val float32) Field
func Float64(key string, val float64) Field
func Float32p(key string, val *float32) Field
func Float64p(key string, val *float64) FieldFloating-point fields and their pointer variants.
func Complex64(key string, val complex64) Field
func Complex128(key string, val complex128) Field
func Complex64p(key string, val *complex64) Field
func Complex128p(key string, val *complex128) FieldComplex number fields (note: these allocate to convert to interface{}).
func ByteString(key string, val []byte) Field
func Binary(key string, val []byte) Fieldfunc Time(key string, val time.Time) Field
func Timep(key string, val *time.Time) FieldTime fields for timestamps.
func Duration(key string, val time.Duration) Field
func Durationp(key string, val *time.Duration) FieldDuration fields for time intervals. Encoding format depends on encoder configuration.
func Bools(key string, bs []bool) Field
func ByteStrings(key string, bss [][]byte) Field
func Ints(key string, nums []int) Field
func Int8s(key string, nums []int8) Field
func Int16s(key string, nums []int16) Field
func Int32s(key string, nums []int32) Field
func Int64s(key string, nums []int64) Field
func Uints(key string, nums []uint) Field
func Uint8s(key string, nums []uint8) Field
func Uint16s(key string, nums []uint16) Field
func Uint32s(key string, nums []uint32) Field
func Uint64s(key string, nums []uint64) Field
func Uintptrs(key string, nums []uintptr) Field
func Float32s(key string, nums []float32) Field
func Float64s(key string, nums []float64) Field
func Complex64s(key string, nums []complex64) Field
func Complex128s(key string, nums []complex128) Field
func Durations(key string, ds []time.Duration) FieldArray fields for slices of primitive types.
func Error(err error) Field
func NamedError(key string, err error) Field
func Errors(key string, errs []error) FieldNamedError("error", err)err.Error() and verbose format for errors implementing fmt.Formatterfunc Object(key string, val zapcore.ObjectMarshaler) Field
func Objects[T zapcore.ObjectMarshaler](key string, values []T) Field
func ObjectValues[T any, P ObjectMarshalerPtr[T]](key string, values []T) Fieldzapcore.ObjectMarshalerObjectMarshaler directlyObjectMarshalerfunc Array(key string, val zapcore.ArrayMarshaler) FieldCustom array implementing zapcore.ArrayMarshaler.
func Dict(key string, val ...Field) Field
func DictObject(val ...Field) zapcore.ObjectMarshalerfunc Inline(val zapcore.ObjectMarshaler) FieldInline object fields into the current namespace (no key wrapping).
func Any(key string, value interface{}) FieldAutomatically detect the type of the value and use the appropriate field constructor. Falls back to reflection for unknown types. Use specific constructors when type is known for better performance.
func Reflect(key string, val interface{}) FieldExplicitly use reflection to serialize the value (slow, allocates).
func Stringer(key string, val fmt.Stringer) FieldField for types implementing fmt.Stringer. Calls String() lazily during encoding.
func Stringers[T fmt.Stringer](key string, values []T) FieldGeneric field for arrays of types implementing fmt.Stringer. Each element's String() method is called during encoding.
Example:
var requests []Request = ...
logger.Info("sending requests", zap.Stringers("requests", requests))Note: The String() method must be declared on the value type (e.g., Request), not its pointer (*Request).
func Stack(key string) Field
func StackSkip(key string, skip int) Fieldskip framesfunc Namespace(key string) FieldCreate a namespace for subsequent fields. All fields added after a namespace field will be nested under that key.
Example:
logger.Info("user event",
zap.String("event", "login"),
zap.Namespace("user"),
zap.String("id", "123"),
zap.String("name", "alice"),
)
// Produces: {"event":"login", "user":{"id":"123", "name":"alice"}}func Skip() FieldNo-op field that is ignored during encoding. Useful for conditional field inclusion.
logger.Info("user action",
zap.String("username", "alice"),
zap.Int("age", 30),
zap.Bool("premium", true),
zap.Float64("balance", 123.45),
zap.Time("timestamp", time.Now()),
)var name *string // nil
var count *int = new(int)
*count = 42
logger.Info("data",
zap.Stringp("name", name), // Safely handles nil
zap.Intp("count", count), // Logs 42
)logger.Info("metrics",
zap.Ints("response_codes", []int{200, 200, 404, 500}),
zap.Durations("latencies", []time.Duration{
100 * time.Millisecond,
250 * time.Millisecond,
50 * time.Millisecond,
}),
)err := errors.New("connection refused")
logger.Error("operation failed",
zap.Error(err), // Adds field with key "error"
)
logger.Error("multiple operations failed",
zap.Errors("errors", []error{err1, err2, err3}),
)type User struct {
ID int
Name string
}
func (u User) MarshalLogObject(enc zapcore.ObjectEncoder) error {
enc.AddInt("id", u.ID)
enc.AddString("name", u.Name)
return nil
}
user := User{ID: 123, Name: "alice"}
logger.Info("user created", zap.Object("user", user))logger.Info("request",
zap.Dict("headers",
zap.String("Content-Type", "application/json"),
zap.String("Authorization", "Bearer token"),
),
zap.Dict("query",
zap.String("page", "1"),
zap.String("limit", "20"),
),
)logger.Info("api request",
zap.String("method", "POST"),
zap.String("path", "/api/users"),
zap.Namespace("request"),
zap.String("content_type", "application/json"),
zap.Int("content_length", 1024),
zap.Namespace("response"),
zap.Int("status", 201),
zap.Duration("latency", 100*time.Millisecond),
)var data interface{} = map[string]int{"count": 42}
logger.Info("data received",
zap.Any("data", data), // Automatically detects type
)func logEvent(logger *zap.Logger, event string, debug bool, debugInfo string) {
fields := []zap.Field{
zap.String("event", event),
}
if debug {
fields = append(fields, zap.String("debug_info", debugInfo))
} else {
fields = append(fields, zap.Skip())
}
logger.Info("event occurred", fields...)
}zap.String() is faster than zap.Any() for stringsComplex64 and Complex128 allocate to convert to interface{}Reflect() in hot paths; use specific constructors or implement ObjectMarshalerFor complex types, implement zapcore.ObjectMarshaler for efficient, type-safe serialization:
type Request struct {
Method string
URL string
Headers map[string]string
}
func (r Request) MarshalLogObject(enc zapcore.ObjectEncoder) error {
enc.AddString("method", r.Method)
enc.AddString("url", r.URL)
return enc.AddObject("headers", zapcore.ObjectMarshalerFunc(func(enc zapcore.ObjectEncoder) error {
for k, v := range r.Headers {
enc.AddString(k, v)
}
return nil
}))
}
// Usage
req := Request{Method: "GET", URL: "/api/users", Headers: map[string]string{"Authorization": "Bearer token"}}
logger.Info("request received", zap.Object("request", req))