zapr – github.com/go-logr/zapr Index | Examples | Files | Directories

package zapr

import "github.com/go-logr/zapr"

Package zapr defines an implementation of the github.com/go-logr/logr interfaces built on top of Zap (go.uber.org/zap).

Usage

A new logr.Logger can be constructed from an existing zap.Logger using the NewLogger function:

log := zapr.NewLogger(someZapLogger)

Implementation Details

For the most part, concepts in Zap correspond directly with those in logr.

Unlike Zap, all fields *must* be in the form of sugared fields -- it's illegal to pass a strongly-typed Zap field in a key position to any of the log methods.

Levels in logr correspond to custom debug levels in Zap. Any given level in logr is represents by its inverse in zap (`zapLevel = -1*logrLevel`). For example V(2) is equivalent to log level -2 in Zap, while V(1) is equivalent to Zap's DebugLevel.

Index

Examples

Functions

func NewLogger

func NewLogger(l *zap.Logger) logr.Logger

NewLogger creates a new logr.Logger using the given Zap Logger to log.

Example

Code:play 

package main

import (
	"errors"
	"time"

	"github.com/go-logr/zapr"
	"github.com/go-logr/zapr/internal/types"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var errSome = errors.New("some error")

func encodeTime(_ time.Time, enc zapcore.PrimitiveArrayEncoder) {

	enc.AppendString("TIMESTAMP")
}

func buildZapLogger() *zap.Logger {

	zc := zap.NewProductionConfig()
	zc.OutputPaths = []string{"stdout"}
	zc.ErrorOutputPaths = zc.OutputPaths
	zc.DisableStacktrace = true
	zc.DisableCaller = true
	zc.EncoderConfig.EncodeTime = encodeTime
	z, _ := zc.Build()
	return z
}

func main() {
	log := zapr.NewLogger(buildZapLogger())
	log.Info("info message with default options")
	log.Error(errSome, "error message with default options")
	log.Info("support for zap fields as key/value replacement is disabled", zap.Int("answer", 42))
	log.Info("invalid key", 42, "answer")
	log.Info("missing value", "answer")
	obj := types.ObjectRef{Name: "john", Namespace: "doe"}
	log.Info("marshaler", "stringer", obj.String(), "raw", obj)
}

Output:

{"level":"info","ts":"TIMESTAMP","msg":"info message with default options"}
{"level":"error","ts":"TIMESTAMP","msg":"error message with default options","error":"some error"}
{"level":"dpanic","ts":"TIMESTAMP","msg":"strongly-typed Zap Field passed to logr","zap field":{"Key":"answer","Type":11,"Integer":42,"String":"","Interface":null}}
{"level":"info","ts":"TIMESTAMP","msg":"support for zap fields as key/value replacement is disabled"}
{"level":"dpanic","ts":"TIMESTAMP","msg":"non-string key argument passed to logging, ignoring all later arguments","invalid key":42}
{"level":"info","ts":"TIMESTAMP","msg":"invalid key"}
{"level":"dpanic","ts":"TIMESTAMP","msg":"odd number of arguments passed as key-value pairs for logging","ignored key":"answer"}
{"level":"info","ts":"TIMESTAMP","msg":"missing value"}
{"level":"info","ts":"TIMESTAMP","msg":"marshaler","stringer":"doe/john","raw":{"name":"john","namespace":"doe"}}

func NewLoggerWithOptions

func NewLoggerWithOptions(l *zap.Logger, opts ...Option) logr.Logger

NewLoggerWithOptions creates a new logr.Logger using the given Zap Logger to log and applies additional options.

Types

type Option

type Option func(*zapLogger)

Option is one additional parameter for NewLoggerWithOptions.

func AllowZapFields

func AllowZapFields(allowed bool) Option

AllowZapFields controls whether strongly-typed Zap fields may be passed instead of a key/value pair. This is disabled by default because it breaks implementation agnosticism.

Example

Code:play 

package main

import (
	"time"

	"github.com/go-logr/zapr"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

func encodeTime(_ time.Time, enc zapcore.PrimitiveArrayEncoder) {

	enc.AppendString("TIMESTAMP")
}

func buildZapLogger() *zap.Logger {

	zc := zap.NewProductionConfig()
	zc.OutputPaths = []string{"stdout"}
	zc.ErrorOutputPaths = zc.OutputPaths
	zc.DisableStacktrace = true
	zc.DisableCaller = true
	zc.EncoderConfig.EncodeTime = encodeTime
	z, _ := zc.Build()
	return z
}

func main() {
	log := zapr.NewLoggerWithOptions(buildZapLogger(), zapr.AllowZapFields(true))
	log.Info("log zap field", zap.Int("answer", 42))
}

Output:

{"level":"info","ts":"TIMESTAMP","msg":"log zap field","answer":42}

func DPanicOnBugs

func DPanicOnBugs(enabled bool) Option

DPanicOnBugs controls whether extra log messages are emitted for invalid log calls with zap's DPanic method. Depending on the configuration of the zap logger, the program then panics after emitting the log message which is useful in development because such invalid log calls are bugs in the program. The log messages explain why a call was invalid (for example, non-string key). Emitting them is enabled by default.

Example

Code:play 

package main

import (
	"time"

	"github.com/go-logr/zapr"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

func encodeTime(_ time.Time, enc zapcore.PrimitiveArrayEncoder) {

	enc.AppendString("TIMESTAMP")
}

func buildZapLogger() *zap.Logger {

	zc := zap.NewProductionConfig()
	zc.OutputPaths = []string{"stdout"}
	zc.ErrorOutputPaths = zc.OutputPaths
	zc.DisableStacktrace = true
	zc.DisableCaller = true
	zc.EncoderConfig.EncodeTime = encodeTime
	z, _ := zc.Build()
	return z
}

func main() {
	log := zapr.NewLoggerWithOptions(buildZapLogger(), zapr.DPanicOnBugs(false))
	log.Info("warnings suppressed", zap.Int("answer", 42))
}

Output:

{"level":"info","ts":"TIMESTAMP","msg":"warnings suppressed"}

func ErrorKey

func ErrorKey(key string) Option

ErrorKey replaces the default "error" field name used for the error in Logger.Error calls.

Example

Code:play 

package main

import (
	"errors"
	"time"

	"github.com/go-logr/zapr"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var errSome = errors.New("some error")

func encodeTime(_ time.Time, enc zapcore.PrimitiveArrayEncoder) {

	enc.AppendString("TIMESTAMP")
}

func buildZapLogger() *zap.Logger {

	zc := zap.NewProductionConfig()
	zc.OutputPaths = []string{"stdout"}
	zc.ErrorOutputPaths = zc.OutputPaths
	zc.DisableStacktrace = true
	zc.DisableCaller = true
	zc.EncoderConfig.EncodeTime = encodeTime
	z, _ := zc.Build()
	return z
}

func main() {
	log := zapr.NewLoggerWithOptions(buildZapLogger(), zapr.ErrorKey("err"))
	log.Error(errSome, "error message with non-default error key")
}

Output:

{"level":"error","ts":"TIMESTAMP","msg":"error message with non-default error key","err":"some error"}

func LogInfoLevel

func LogInfoLevel(key string) Option

LogInfoLevel controls whether a numeric log level is added to Info log message. The empty string disables this, a non-empty string is the key for the additional field. Errors and internal panic messages do not have a log level and thus are always logged without this extra field.

Example

Code:play 

package main

import (
	"errors"
	"time"

	"github.com/go-logr/zapr"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var errSome = errors.New("some error")

func encodeTime(_ time.Time, enc zapcore.PrimitiveArrayEncoder) {

	enc.AppendString("TIMESTAMP")
}

func buildZapLogger() *zap.Logger {

	zc := zap.NewProductionConfig()
	zc.OutputPaths = []string{"stdout"}
	zc.ErrorOutputPaths = zc.OutputPaths
	zc.DisableStacktrace = true
	zc.DisableCaller = true
	zc.EncoderConfig.EncodeTime = encodeTime
	z, _ := zc.Build()
	return z
}

func main() {
	log := zapr.NewLoggerWithOptions(buildZapLogger(), zapr.LogInfoLevel("v"))
	log.Info("info message with numeric verbosity level")
	log.Error(errSome, "error messages have no numeric verbosity level")
}

Output:

{"level":"info","ts":"TIMESTAMP","msg":"info message with numeric verbosity level","v":0}
{"level":"error","ts":"TIMESTAMP","msg":"error messages have no numeric verbosity level","error":"some error"}

type Underlier

type Underlier interface {
	GetUnderlying() *zap.Logger
}

Underlier exposes access to the underlying logging implementation. Since callers only have a logr.Logger, they have to know which implementation is in use, so this interface is less of an abstraction and more of way to test type conversion.

Source Files

slogzapr.go zapr.go zapr_slog.go

Directories

PathSynopsis
exampleThis example shows how to instantiate a zap logger and what output looks like.
internal
Version
v1.3.0 (latest)
Published
Nov 3, 2023
Platform
js/wasm
Imports
8 packages
Last checked
3 days ago

Tools for package owners.