or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

configuration.mdfields.mdindex.mdintegrations.mdlogger.mdtesting.mdzapcore.md
tile.json

fields.mddocs/

Field Constructors

Zap uses strongly-typed fields to avoid reflection and allocations during logging. Each field constructor creates a Field value that efficiently encodes typed data.

Field Type

type Field = zapcore.Field

Fields are the core unit of structured logging context in zap. All Logger methods accept variadic Field arguments.

Primitive Type Fields

String Fields

func String(key string, val string) Field
func Stringp(key string, val *string) Field
  • String: String field
  • Stringp: String pointer field (safely handles nil)

Integer Fields

func 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) Field

Signed integer fields and their pointer variants.

Unsigned Integer Fields

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) Field

Unsigned integer fields and their pointer variants.

Boolean Fields

func Bool(key string, val bool) Field
func Boolp(key string, val *bool) Field

Boolean field and pointer variant.

Floating-Point Fields

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) Field

Floating-point fields and their pointer variants.

Complex Number Fields

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) Field

Complex number fields (note: these allocate to convert to interface{}).

Byte and Binary Fields

func ByteString(key string, val []byte) Field
func Binary(key string, val []byte) Field
  • ByteString: UTF-8 encoded text as []byte
  • Binary: Opaque binary data (base64-encoded in JSON)

Temporal Type Fields

Time Fields

func Time(key string, val time.Time) Field
func Timep(key string, val *time.Time) Field

Time fields for timestamps.

Duration Fields

func Duration(key string, val time.Duration) Field
func Durationp(key string, val *time.Duration) Field

Duration fields for time intervals. Encoding format depends on encoder configuration.

Array Fields

Primitive Array Fields

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) Field

Array fields for slices of primitive types.

Error Fields

Error Field Functions

func Error(err error) Field
func NamedError(key string, err error) Field
func Errors(key string, errs []error) Field
  • Error: Shorthand for NamedError("error", err)
  • NamedError: Error with custom key; stores err.Error() and verbose format for errors implementing fmt.Formatter
  • Errors: Slice of errors

Object and Custom Type Fields

Object Marshaler Fields

func 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) Field
  • Object: Custom object implementing zapcore.ObjectMarshaler
  • Objects: Slice of objects where the type implements ObjectMarshaler directly
  • ObjectValues: Slice of objects where pointers to the type implement ObjectMarshaler

Array Marshaler Fields

func Array(key string, val zapcore.ArrayMarshaler) Field

Custom array implementing zapcore.ArrayMarshaler.

Dictionary Fields

func Dict(key string, val ...Field) Field
func DictObject(val ...Field) zapcore.ObjectMarshaler
  • Dict: Create a dictionary/map field from other fields
  • DictObject: Create an ObjectMarshaler from fields (for use with Object or Objects)

Inline Fields

func Inline(val zapcore.ObjectMarshaler) Field

Inline object fields into the current namespace (no key wrapping).

Reflection-Based Fields

Any Field

func Any(key string, value interface{}) Field

Automatically 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.

Reflect Field

func Reflect(key string, val interface{}) Field

Explicitly use reflection to serialize the value (slow, allocates).

Stringer Field

func Stringer(key string, val fmt.Stringer) Field

Field for types implementing fmt.Stringer. Calls String() lazily during encoding.

Stringers Field

func Stringers[T fmt.Stringer](key string, values []T) Field

Generic 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).

Stack Trace Fields

func Stack(key string) Field
func StackSkip(key string, skip int) Field
  • Stack: Capture stack trace at call site
  • StackSkip: Capture stack trace, skipping skip frames

Namespace Field

func Namespace(key string) Field

Create 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"}}

Skip Field

func Skip() Field

No-op field that is ignored during encoding. Useful for conditional field inclusion.

Usage Examples

Basic Field Usage

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()),
)

Pointer Fields (Handling Nil)

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
)

Array Fields

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,
    }),
)

Error Fields

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}),
)

Object Marshaler

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

Dictionary Fields

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"),
    ),
)

Namespaced Fields

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),
)

Using Any for Unknown Types

var data interface{} = map[string]int{"count": 42}

logger.Info("data received",
    zap.Any("data", data),  // Automatically detects type
)

Conditional Fields with Skip

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...)
}

Performance Considerations

  • Prefer specific constructors over Any: zap.String() is faster than zap.Any() for strings
  • Pointer variants handle nil safely: No need for manual nil checks
  • Complex types allocate: Complex64 and Complex128 allocate to convert to interface{}
  • Reflect is slow: Avoid Reflect() in hot paths; use specific constructors or implement ObjectMarshaler
  • Array fields are efficient: No allocations for primitive array types
  • Object/Array marshalers are lazy: Evaluation is deferred until encoding, so they're safe in disabled log statements

Custom Object Marshaling

For 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))