zapx

package
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2026 License: Apache-2.0 Imports: 12 Imported by: 4

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// StringKeyf is an alias for [Stringkf] using a longer, more consistent name.
	//
	// See [Stringkf] for more details.
	StringKeyf = Stringkf

	// StringerKeyf is an alias for [Stringerkf] using a longer, more consistent name.
	//
	// See [Stringerkf] for more details.
	StringerKeyf = Stringerkf
)

Functions

func DPanicf

func DPanicf(logger *zap.Logger, msg string, args []any, fields ...zap.Field)

DPanicf logs a dpanic-level message with formatting and optional fields.

Example:

zapx.DPanicf(zlog, "User %s logged in from %s", []any{userName, ipAddress}, zap.String("user_id", userID))

func Debugf

func Debugf(logger *zap.Logger, msg string, args []any, fields ...zap.Field)

Debugf logs a debug-level message with formatting and optional fields.

Example:

zapx.Debugf(zlog, "User %s logged in from %s", []any{userName, ipAddress}, zap.String("user_id", userID))

Important: This is not recommended for high-frequency debug logs as the formatting is done eagerly.

func Errorf

func Errorf(logger *zap.Logger, msg string, args []any, fields ...zap.Field)

Errorf logs a error-level message with formatting and optional fields.

Example:

zapx.Errorf(zlog, "User %s logged in from %s", []any{userName, ipAddress}, zap.String("user_id", userID))

Important: This is not recommended for high-frequency error logs as the formatting is done eagerly.

func HumanDuration

func HumanDuration(name string, duration time.Duration) zap.Field

HumanDuration prints the duration as compact humanize format where the unit is present and where decimals are used for precision. The actual precision is always truncated to 2 digits so this logging loses precisions in most cases.

- If the duration is smaller than 0.1s, prints in milliseconds with 2 digits precision. - If the duration is smaller than 60s but bigger than 0.1s, prints in seconds with 2 digits precision with `s` as suffix. - If the duration is smaller than 120m but bigger than 60s, prints in minutes + seconds with 2 digits precision (e.g. 30m 45.55s). - Otherwise, prints as hour + minutes + seconds with 2 digits precision (e.g. 20h 40m 54.34s).

Trailing zeros as not printed from the decimal portion is present.

func Infof

func Infof(logger *zap.Logger, msg string, args []any, fields ...zap.Field)

Infof logs a info-level message with formatting and optional fields.

Example:

zapx.Infof(zlog, "User %s logged in from %s", []any{userName, ipAddress}, zap.String("user_id", userID))

Important: This is not recommended for high-frequency info logs as the formatting is done eagerly.

func Panicf

func Panicf(logger *zap.Logger, msg string, args []any, fields ...zap.Field)

Panicf logs a panic-level message with formatting and optional fields.

Example:

zapx.Panicf(zlog, "User %s logged in from %s", []any{userName, ipAddress}, zap.String("user_id", userID))

func Proto

func Proto(name string, value proto.Message, opts ...ProtoFieldOption) zap.Field

Proto can be used to create a zap.Field that marshals a protobuf message into a string representation. The field can be rendered in either JSON or text format, depending on the options provided.

This is a finer control version of zap.Reflect when you deal with protobuf messages. It is lazy loaded deferring the marshaling until the field is actually needed for a logger.

By default shows the in compact text format, but you can use the ProtoPretty option to render it in a pretty format with indentation and multiline support:

zapx.Proto("field", myProtoMessage, zapx.ProtoPretty())

You set it to render in JSON format by using the ProtoMarshalerJSON option:

zapx.Proto("field", myProtoMessage, zapx.ProtoMarshalerJSON())

Note: Think about using ProtoJSON instead of this function if you want to render the protobuf message in JSON format.

Finally you can use the ProtoResolver option to set a custom resolver for the proto field, which is useful if you have custom message types or extensions that need to be resolved during marshaling:

zapx.Proto("field", myProtoMessage, zapx.ProtoResolver(myResolver))

func ProtoJSON

func ProtoJSON(name string, value proto.Message, opts ...ProtoFieldOption) zap.Field

ProtoJSON is a convenience function that creates a zap.Field for a protobuf message in JSON format, convenience for `zapx.Proto(name, value, zapx.ProtoMarshalerJSON())`.

See Proto for full documentation on how to use this function.

func Secret

func Secret(name string, value string) zap.Field

Secret creates a zap field for logging secret values with redaction. It shows approximately 25% of characters from the start and 10% from the end, with the middle replaced by asterisks.

Example:

logger.Info("API connection", zapx.Secret("api_key", "ac_fake_abcdefghijklmnopqrstuvwxyz123456"))
// Logs: {"api_key": "ac_fake_abc***3456"}

func Stringerkf

func Stringerkf(format string, stringer fmt.Stringer, args ...any) zap.Field

Stringerkf creates a zap field with a fmt.Stringer value and a key formatted using fmt.Sprintf.

It's important to note that the key formatting is performed immediately when the field is created, not deferred. This means that any computation involved in formatting the key will occur even if the field is not logged.

Important: This is not recommended for high-frequency trace logs as the formatting is done eagerly.

Example:

zlog.Info("User logged in", zapx.Stringerkf("user_%d", userStringer, userID))

func Stringf

func Stringf(name string, valueFormat string, args ...any) zap.Field

Stringf creates a zap field with a string value formatted using fmt.Sprintf. The formatting is deferred until the field is actually serialized, which can save computation if the field is not logged.

Example:

zlog.Info("User logged in", zapx.Stringf("welcome_message", "Hello, %s!", userName))

func Stringkf

func Stringkf(format string, value string, args ...any) zap.Field

Stringkf creates a zap field with a string value and a key formatted using fmt.Sprintf.

It's important to note that the key formatting is performed immediately when the field is created, not deferred. This means that any computation involved in formatting the key will occur even if the field is not logged.

Important: This is not recommended for high-frequency trace logs as the formatting is done eagerly.

Example:

zlog.Info("User logged in", zapx.Stringkf("welcome_message_%d", value, userID))

func Trace

func Trace(logger *zap.Logger, tracer logging.Tracer, msg string, fields ...zap.Field)

Trace logs a trace-level message optional fields.

Example:

var zlog, tracer = logging.PackageLogger("name", "component")
zapx.Trace(zlog, tracer, "User logged in", zap.String("user_id", userID))

This replaces the following pattern:

if tracer.Enabled() {
    zlog.Debug("User logged in", zap.String("user_id", userID))
}

And should be as efficient since the check is done before any field evaluation and inlining should remove any overhead.

func Tracef

func Tracef(logger *zap.Logger, tracer logging.Tracer, msg string, args []any, fields ...zap.Field)

Tracef logs a trace-level message with formatting and optional fields.

Example:

var zlog, tracer = logging.PackageLogger("name", "component")
zapx.Tracef(zlog, tracer, "User %s logged in from %s", []any{userName, ipAddress}, zap.String("user_id", userID))

This replaces the following pattern:

if tracer.Enabled() {
    zlog.Debug(fmt.Sprintf("User %s logged in from %s", []any{userName, ipAddress}, zap.String("user_id", userID))
}

And should be as efficient since the check is done before any field evaluation and inlining should remove any overhead.

Important: This is not recommended for high-frequency trace logs as the formatting is done eagerly.

func TruncatedString

func TruncatedString(fieldName string, value string, maxLength int) zap.Field

TruncatedString creates a zap.Field that truncates a string value to a maximum length. The truncation is performed lazily when the field is actually logged, using zap's lazy loading mechanism through the String() method.

If the string is shorter than or equal to maxLength, it is returned as-is. If the string is longer than maxLength, it is truncated to maxLength characters.

Example usage:

logger.Info("Processing data", zapx.TruncatedString("data", longString, 100))

func TruncatedStringer added in v1.2.1

func TruncatedStringer(fieldName string, stringer fmt.Stringer, maxLength int) zap.Field

TruncatedStringer creates a zap.Field that truncates a fmt.Stringer value to a maximum length. The truncation is performed lazily when the field is actually logged, using zap's lazy loading mechanism through the String() method.

If the string representation of the fmt.Stringer is shorter than or equal to maxLength, it is returned as-is. If it is longer than maxLength, it is truncated to maxLength characters.

Example usage:

logger.Info("Processing data", zapx.TruncatedStringer("data", longStringer, 100))

func Type

func Type(name string, value any) zap.Field

Type returns a zap.Field that for which is going to render the field "<name>": "<type name of value>" where `<type name of value>` is going to be the `reflect.TypeOf(value).String()`.

The field is lazy and will not be evaluated until the field is actually logged, which is useful for performance reasons.

func Warnf

func Warnf(logger zap.Logger, msg string, args []any, fields ...zap.Field)

Warnf logs a warn-level message with formatting and optional fields.

Example:

zapx.Warnf(zlog, "User %s logged in from %s", []any{userName, ipAddress}, zap.String("user_id", userID))

Important: This is not recommended for high-frequency warn logs as the formatting is done eagerly.

Types

type ProtoFieldMarshalerKind

type ProtoFieldMarshalerKind string
const (
	ProtoFieldTextMarshaler ProtoFieldMarshalerKind = "text"
	ProtoFieldJSONMarshaler ProtoFieldMarshalerKind = "json"
)

type ProtoFieldOption

type ProtoFieldOption interface {
	Apply(*ProtoFieldOptions)
}

func ProtoMarshalerJSON

func ProtoMarshalerJSON() ProtoFieldOption

ProtoMarshalerJSON can be used to render fields on protobuf messages in a pretty format with indentation and multiline support.

zapx.Proto("field", myProtoMessage, zapx.ProtoMarshalerJSON())

func ProtoPretty

func ProtoPretty() ProtoFieldOption

ProtoPretty can be used to render fields on protobuf messages in a pretty format with indentation and multiline support.

zapx.Proto("field", myProtoMessage, zapx.ProtoPretty())

func ProtoResolver

ProtoResolver can be used to set a custom resolver for the proto field.

zapx.Proto("field", myProtoMessage, zapx.ProtoResolver(myResolver))

type ProtoFieldOptionFunc

type ProtoFieldOptionFunc func(*ProtoFieldOptions)

func (ProtoFieldOptionFunc) Apply

func (f ProtoFieldOptionFunc) Apply(opts *ProtoFieldOptions)

type ProtoFieldOptions

type ProtoFieldOptions struct {
	// Indent is the string used for indentation in pretty printing,
	// if empty, defaults is no indentation (compact format).
	Indent string

	// Resolver is used to resolve message types and extensions.
	Resolver interface {
		protoregistry.ExtensionTypeResolver
		protoregistry.MessageTypeResolver
	}

	// MarshalerKind specifies the kind of marshaling to use for the proto field,
	// either zapx.ProtoFieldTextMarshaler or zapx.ProtoFieldJSONMarshaler, defaults
	// is text marshaling.
	MarshalerKind ProtoFieldMarshalerKind

	// AllowPartial allows messages that have missing required fields to marshal
	// without returning an error. If AllowPartial is false,
	// Marshal will return error if there are any missing required fields. Defaults
	// is true.
	AllowPartial bool

	// EmitUnpopulated specifies whether unpopulated fields should be emitted,
	// defaults to false (applies to JSON marshaling only).
	EmitUnpopulated bool
}

func (*ProtoFieldOptions) ToProtoJSONMarshalOptions

func (opts *ProtoFieldOptions) ToProtoJSONMarshalOptions() protojson.MarshalOptions

func (*ProtoFieldOptions) ToProtoTextMarshalOptions

func (opts *ProtoFieldOptions) ToProtoTextMarshalOptions() prototext.MarshalOptions

type SecretString

type SecretString string

SecretString is a string wrapper that redacts most of its content when converted to a string, showing only a portion at the beginning and end. This is useful for logging sensitive data like API keys, tokens, or passwords while maintaining some visibility for debugging.

The String() method shows approximately 25% of characters from the start and 10% from the end (minimum 1 character at the end), with the middle replaced by asterisks.

Example usage:

apiKey := zapx.SecretString("ac_fake_abcdefghijklmnopqrstuvwxyz123456")
fmt.Println(apiKey) // Output: ac_fake_abc***3456

func (SecretString) String

func (s SecretString) String() string

Jump to

Keyboard shortcuts

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