zlog

package
v2.16.0 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2024 License: MIT Imports: 26 Imported by: 5

Documentation

Overview

Package zlog provides opinionated high-level logging facilities based on go.uber.org/zap.

Logger and SugaredLogger are simple wrappers of *zap.Logger and *zap.SugaredLogger, to provide more user-friendly API in addition to zap.

TraceLevel

This package defines an extra TraceLevel, for the most fine-grained information which helps developer "tracing" their code. Users can expect this logging level to be very verbose, you can use it, for example, to annotate each step in an algorithm or each individual calling with parameters in your program.

In production deployment, it's strongly suggested to disable TraceLevel logs. In development, user may also configure to only allow or deny TraceLevel messages from some packages or some files to reduce the number of tracing logs. See Logger.Trace, SugaredLogger.Tracef, TRACE, GlobalConfig.TraceFilterRule for detailed documents.

Dynamic Level

This package supports changing logging level dynamically, in two ways:

  1. Loggers creates by this package wraps the zap Core by a dynamic-level Core. User can use Config.PerLoggerLevels to configure different level for different loggers by logger names. The format is "loggerName.subLogger=level". If a level is configured for a parent logger, bug not configured for a child logger, the child logger derives from its parent.
  2. GlobalConfig.CtxHandler, if configured, can optionally change level according to contextual information, by returning a non-nil CtxResult.Level value.

Context Integration

This package integrates with context.Context, user may add contextual fields to a Context (see AddFields, CtxHandler), or add a pre-built logger to a Context (see WithLogger), or set a Context to use dynamic level (see CtxHandler), either smaller or greater than the base logger. Functions Logger.Ctx, SugaredLogger.Ctx and WithCtx create child loggers with contextual information retrieved from a Context.

Multi-files Support

Config.PerLoggerFiles optionally set different file destination for different loggers specified by logger name. If a destination is configured for a parent logger, but not configured for a child logger, the child logger derives from its parent.

"logfmt" Encoder

NewLogfmtEncoder creates a zapcore.Encoder which encodes log in the "logfmt" format. The returned encoder does not support zapcore.ObjectMarshaler.

"logr" Adapter

This package provides an adapter implementation of logr.LogSink to send logs from a logr.Logger to an underlying zap.Logger.

NewLogrLogger accepts optional options and creates a new logr.Logger using a zap.Logger as the underlying LogSink.

"slog" Adapter

This package provides an adapter implementation of slog.Handler to send logs from a slog.Logger to an underlying zap.Logger.

NewSlogLogger accepts optional options and creates a new slog.Logger using a zap.Logger as the underlying Handler.

Example

func main() {
	// Simple shortcut for development.
	zlog.SetDevelopment()

 	// Or, provide complete config and options to configure it.
	logCfg := &zlog.Config{ /* ... */ }
	logOpts := []zap.Option{ /* ... */ }
	zlog.SetupGlobals(logCfg, logOpts...)

	// Use the loggers ...
	zlog.L() /* ... */
	zlog.S() /* ... */
	zlog.With( ... ) /* ... */
	zlog.SugaredWith( ... ) /* ... */

	// Use with context integration.
	ctx = zlog.AddFields(ctx, ... ) // or ctx = zlog.WithLogger( ... )
	zlog.L().Ctx(ctx) /* ... */
	zlog.S().Ctx(ctx) /* ... */
	zlog.WithCtx(ctx) /* ... */

	// logr
	logger := zlog.NewLogrLogger( /* ... */ )

	// slog
	logger := zlog.NewSlogLogger( /* ... */ )

	// ......
}

Index

Examples

Constants

View Source
const (
	// TraceLevel logs are the most fine-grained information which helps
	// developer "tracing" their code.
	// Users can expect this level to be very verbose, you can use it,
	// for example, to annotate each step in an algorithm or each individual
	// calling with parameters in your program.
	// TraceLevel logs should be disabled in production.
	TraceLevel Level = -2

	// DebugLevel logs are typically voluminous, and are usually disabled in
	// production.
	DebugLevel = zapcore.DebugLevel
	// InfoLevel is the default logging priority.
	InfoLevel = zapcore.InfoLevel
	// WarnLevel logs are more important than Info, but don't need individual
	// human review.
	WarnLevel = zapcore.WarnLevel
	// ErrorLevel logs are high-priority. If an application is running smoothly,
	// it shouldn't generate any error-level logs.
	ErrorLevel = zapcore.ErrorLevel
	// DPanicLevel logs are particularly important errors. In development the
	// logger panics after writing the message.
	DPanicLevel = zapcore.DPanicLevel
	// PanicLevel logs a message, then panics.
	PanicLevel = zapcore.PanicLevel
	// FatalLevel logs a message, then calls os.Exit(1).
	FatalLevel = zapcore.FatalLevel
)
View Source
const TraceFilterRuleEnvName = "ZLOG_TRACE_FILTER_RULE"

Variables

View Source
var ErrUnsupportedValueType = errors.New("unsupported value type")

Functions

func AddFields added in v2.7.4

func AddFields(ctx context.Context, fields ...zap.Field) context.Context

AddFields add logging fields to ctx which can be retrieved by GetFields, WithCtx. Duplicate fields override the old ones in ctx.

Example
defer testHelperReplaceGlobalsToStdout(nil)()

ctx := context.Background()
ctx = AddFields(ctx,
	zap.String("ctx1", "v1"),
	zap.Int64("ctx2", 123))
ctx = AddFields(ctx,
	zap.String("k3", "v3"),         // add a new field
	zap.String("ctx2", "override"), // override "ctx2"
)
logger := WithCtx(ctx)
logger.Info("example AddFields")
Output:

{"level":"info","msg":"example AddFields","ctx1":"v1","ctx2":"override","k3":"v3"}

func CloseWriters added in v2.13.0

func CloseWriters()

CloseWriters close all writers opened by the global logger.

func ConvertAttrToField added in v2.14.3

func ConvertAttrToField(attr slog.Attr) zapcore.Field

ConvertAttrToField converts a slog.Attr to a zap.Field.

func ConvertFieldToAttr added in v2.15.1

func ConvertFieldToAttr(field zapcore.Field) slog.Attr

func DPanic

func DPanic(msg string, fields ...zap.Field)

func DPanicf

func DPanicf(format string, args ...any)

func DPanicw added in v2.15.1

func DPanicw(msg string, keysAndValues ...any)

func Debug

func Debug(msg string, fields ...zap.Field)

func Debugf

func Debugf(format string, args ...any)

func Debugw added in v2.15.1

func Debugw(msg string, keysAndValues ...any)

func Error

func Error(msg string, fields ...zap.Field)

func Errorf

func Errorf(format string, args ...any)

func Errorw added in v2.15.1

func Errorw(msg string, keysAndValues ...any)

func Fatal

func Fatal(msg string, fields ...zap.Field)

func Fatalf

func Fatalf(format string, args ...any)

func Fatalw added in v2.15.1

func Fatalw(msg string, keysAndValues ...any)

func GetFields added in v2.7.4

func GetFields(ctx context.Context) []zap.Field

GetFields returns the logging fields added to ctx by AddFields.

func Info

func Info(msg string, fields ...zap.Field)

func Infof

func Infof(format string, args ...any)

func Infow added in v2.15.1

func Infow(msg string, keysAndValues ...any)

func NewLogfmtEncoder

func NewLogfmtEncoder(cfg zapcore.EncoderConfig) zapcore.Encoder

NewLogfmtEncoder creates a zapcore.Encoder which encodes log in the "logfmt" format. The returned encoder does not support zapcore.ObjectMarshaler.

func NewLogrLogger added in v2.13.0

func NewLogrLogger(options ...func(*LogrOptions)) logr.Logger

NewLogrLogger creates a new logr.Logger.

func NewSlogLogger added in v2.14.3

func NewSlogLogger(options ...func(*SlogOptions)) *slog.Logger

NewSlogLogger creates a new slog.Logger.

func Panic

func Panic(msg string, fields ...zap.Field)

func Panicf

func Panicf(format string, args ...any)

func Panicw added in v2.15.1

func Panicw(msg string, keysAndValues ...any)

func Print

func Print(args ...any)

Print uses fmt.Sprint to log a message at InfoLevel if it's enabled.

It has same signature with log.Print, which helps to migrate from the standard library to this package.

func Printf

func Printf(format string, args ...any)

Printf logs a message at InfoLevel if it's enabled.

It has same signature with log.Printf, which helps to migrate from the standard library to this package.

func Println added in v2.1.0

func Println(args ...any)

Println logs a message at InfoLevel if it's enabled.

It has same signature with log.Println, which helps to migrate from the standard library to this package.

func ReplaceGlobals

func ReplaceGlobals(logger *zap.Logger, props *Properties) func()

ReplaceGlobals replaces the global Logger and SugaredLogger, and returns a function to restore the original values.

It is meant to be called at program startup, library code shall not call this function.

func SetDevelopment

func SetDevelopment()

SetDevelopment is a shortcut of SetupGlobals with default configuration for development. It sets the global logger in development mode, and redirects output from the standard log library's package-global logger to the global logger in this package.

It is meant to be called at program startup, when you run in development mode, for production mode, please check SetupGlobals and ReplaceGlobals.

func SetLevel

func SetLevel(lvl Level)

SetLevel modifies the global logging level on the fly. It's safe for concurrent use.

func SetSlogDefault added in v2.14.3

func SetSlogDefault(l *slog.Logger)

SetSlogDefault replaces the slog package's default logger. Compared to slog.SetDefault, it does not set the log package's default logger to l's handler, instead it sets it's output to an underlying zap.Logger returned by L().

func SetupGlobals

func SetupGlobals(cfg *Config, opts ...zap.Option)

SetupGlobals setups the global loggers in this package and zap library. By default, global loggers are set with default configuration with info level and json format, you may use this function to change the default loggers.

See Config and GlobalConfig for available configurations.

It is meant to be called at program startup, library code shall not call this function.

func Sync

func Sync() error

Sync flushes any buffered log entries.

func TRACE

func TRACE(args ...any)

TRACE logs a message at TraceLevel if it's enabled.

TRACE accepts flexible arguments to help development, it trys to get a logger from the first argument, if the first argument is a *zap.Logger or *zap.SugaredLogger, the logger will be used, else if the first argument is a context.Context, the context will be used to build a logger using Builder, else it uses the global logger.

The other arguments may be of type zap.Field or any ordinary type, the type will be detected and the arguments will be formatted in a most reasonable way. See example code for detailed usage examples.

If trace messages are disabled globally, calling this function is a no-op.

func TRACE1 added in v2.1.0

func TRACE1(arg0 any, args ...any)

TRACE1 is same with TRACE, but it accepts an extra arg0 before args.

func TRACESkip

func TRACESkip(skip int, args ...any)

TRACESkip is similar to TRACE, but it has an extra skip argument to get correct caller information. When you need to wrap TRACE, you will always want to use this function instead of TRACE.

If trace messages are disabled globally, calling this function is a no-op.

func TRACESkip1 added in v2.1.0

func TRACESkip1(skip int, arg0 any, args ...any)

TRACESkip1 is same with TRACESkip, but it accepts an extra arg0 before args.

func Warn

func Warn(msg string, fields ...zap.Field)

func Warnf

func Warnf(format string, args ...any)

func Warnw added in v2.15.1

func Warnw(msg string, keysAndValues ...any)

func WithLogger added in v2.7.4

func WithLogger[T Logger | SugaredLogger | *zap.Logger | *zap.SugaredLogger](
	ctx context.Context, logger T) context.Context

WithLogger returns a new context.Context with logger attached, which can be retrieved by WithCtx.

Types

type Config

type Config struct {
	// Level sets the default logging level for the logger.
	Level string `json:"level" yaml:"level"`

	// PerLoggerLevels optionally configures logging level by logger names.
	// The format is "loggerName.subLogger=level".
	// If a level is configured for a parent logger, but not configured for
	// a child logger, the child logger derives from its parent.
	PerLoggerLevels []string `json:"perLoggerLevels" yaml:"perLoggerLevels"`

	// Format sets the logger's encoding format.
	// Valid values are "json", "console", and "logfmt".
	Format string `json:"format" yaml:"format"`

	// File specifies file log config.
	File FileConfig `json:"file" yaml:"file"`

	// PerLoggerFiles optionally set different file destination for different
	// loggers specified by logger name.
	// If a destination is configured for a parent logger, but not configured
	// for a child logger, the child logger derives from its parent.
	PerLoggerFiles map[string]FileConfig `json:"perLoggerFiles" yaml:"perLoggerFiles"`

	// FileWriterFactory optionally specifies a custom factory function,
	// when File is configured, to open a file to write log.
	// By default, [zap.Open] is used, which does not support file rotation.
	FileWriterFactory FileWriterFactory `json:"-" yaml:"-"`

	// FunctionKey enables logging the function name.
	// By default, function name is not logged.
	FunctionKey string `json:"functionKey" yaml:"functionKey"`

	// Development puts the logger in development mode, which changes the
	// behavior of DPanicLevel and takes stacktrace more liberally.
	Development bool `json:"development" yaml:"development"`

	// DisableTimestamp disables automatic timestamps in output.
	DisableTimestamp bool `json:"disableTimestamp" yaml:"disableTimestamp"`

	// DisableCaller stops annotating logs with the calling function's file
	// name and line number. By default, all logs are annotated.
	DisableCaller bool `json:"disableCaller" yaml:"disableCaller"`

	// DisableStacktrace disables automatic stacktrace capturing.
	DisableStacktrace bool `json:"disableStacktrace" yaml:"disableStacktrace"`

	// StacktraceLevel sets the level that stacktrace will be captured.
	// By default, stacktraces are captured for ErrorLevel and above.
	StacktraceLevel string `json:"stacktraceLeve" yaml:"stacktraceLevel"`

	// Sampling sets a sampling strategy for the logger. Sampling caps the
	// global CPU and I/O load that logging puts on your process while
	// attempting to preserve a representative subset of your logs.
	//
	// Values configured here are per-second. See zapcore.NewSampler for details.
	Sampling *zap.SamplingConfig `json:"sampling" yaml:"sampling"`

	// Hooks registers functions which will be called each time the logger
	// writes out an Entry. Repeated use of Hooks is additive.
	//
	// This offers users an easy way to register simple callbacks (e.g.,
	// metrics collection) without implementing the full Core interface.
	//
	// See zap.Hooks and zapcore.RegisterHooks for details.
	Hooks []func(zapcore.Entry) error `json:"-" yaml:"-"`

	// GlobalConfig configures some global behavior of this package.
	// It works with SetupGlobals and ReplaceGlobals, it has no effect for
	// individual non-global loggers.
	GlobalConfig `yaml:",inline"`
}

Config serializes log related config in json/yaml.

type CtxHandler added in v2.13.0

type CtxHandler struct {

	// ChangeLevel returns a non-nil Level if it wants to change
	// the logger's logging level according to ctx.
	// It returns nil to keep the logger's logging level as-is.
	ChangeLevel func(ctx context.Context) *Level

	// WithCtx is called by Logger.Ctx, SugaredLogger.Ctx and the global
	// function WithCtx to check ctx for context-aware information.
	// It returns CtxResult to customize the logger's behavior.
	WithCtx func(ctx context.Context) CtxResult
}

CtxHandler customizes a logger's behavior at runtime dynamically.

type CtxResult

type CtxResult struct {
	// Non-nil Level changes the logger's logging level.
	Level *Level

	// Fields will be added to the logger as additional fields.
	Fields []zap.Field
}

CtxResult holds information get from a context.

type FileConfig added in v2.13.0

type FileConfig struct {
	// Filename is the file to write logs to, leave empty to disable file log.
	Filename string `json:"filename" yaml:"filename"`

	// MaxSize is the maximum size in MB of the log file before it gets
	// rotated. It defaults to 100 MB.
	MaxSize int `json:"maxSize" yaml:"maxSize"`

	// MaxDays is the maximum days to retain old log files based on the
	// timestamp encoded in their filenames.
	// Note that a day is defined as 24 hours and may not exactly correspond
	// to calendar days due to daylight savings, leap seconds, etc.
	// The default is not to remove old log files.
	MaxDays int `json:"maxDays" yaml:"maxDays"`

	// MaxBackups is the maximum number of old log files to retain.
	// The default is to retain all old log files (though MaxAge may still
	// cause them to get deleted.)
	MaxBackups int `json:"maxBackups" yaml:"maxBackups"`

	// Compress determines if the rotated log files should be compressed.
	// The default is not to perform compression.
	Compress bool `json:"compress" yaml:"compress"`
}

FileConfig serializes file log related config in json/yaml.

type FileWriterFactory added in v2.13.0

type FileWriterFactory func(fc *FileConfig) (zapcore.WriteSyncer, func(), error)

FileWriterFactory opens a file to write log, FileConfig specifies filename and optional settings to rotate the log files. The returned WriteSyncer should be safe for concurrent use, you may use zap.Lock to wrap a WriteSyncer to be concurrent safe. It also returns any error encountered and a function to close the opened file.

User may check github.com/jxskiss/gopkg/_examples/zlog/lumberjack_writer for an example to use "lumberjack.v2" as a rolling logger.

type GlobalConfig

type GlobalConfig struct {
	// RedirectStdLog redirects output from the standard log library's
	// package-global logger to the global logger in this package at
	// InfoLevel.
	RedirectStdLog bool `json:"redirectStdLog" yaml:"redirectStdLog"`

	// MethodNameKey specifies the key to use when adding caller's method
	// name to logging messages. It defaults to "methodName".
	MethodNameKey string `json:"methodNameKey" yaml:"methodNameKey"`

	// TraceFilterRule optionally configures filter rule to allow or deny
	// trace logging in some packages or files.
	//
	// It uses glob to match filename, the syntax is "allow=glob1,glob2;deny=glob3,glob4".
	// For example:
	//
	// - "", empty rule means allow all messages
	// - "allow=all", allow all messages
	// - "deny=all", deny all messages
	// - "allow=pkg1/*,pkg2/*.go",
	//   allow messages from files in `pkg1` and `pkg2`,
	//   deny messages from all other packages
	// - "allow=pkg1/sub1/abc.go,pkg1/sub2/def.go",
	//   allow messages from file `pkg1/sub1/abc.go` and `pkg1/sub2/def.go`,
	//   deny messages from all other files
	// - "allow=pkg1/**",
	//   allow messages from files and sub-packages in `pkg1`,
	//   deny messages from all other packages
	// - "deny=pkg1/**.go,pkg2/**.go",
	//   deny messages from files and sub-packages in `pkg1` and `pkg2`,
	//   allow messages from all other packages
	// - "allow=all;deny=pkg/**", same as "deny=pkg/**"
	//
	// If both "allow" and "deny" directives are configured, the "allow" directive
	// takes effect, the "deny" directive is ignored.
	//
	// The default value is empty, which means all messages are allowed.
	//
	// User can also set the environment variable "ZLOG_TRACE_FILTER_RULE"
	// to configure it at runtime, if available, the environment variable
	// is used when this value is empty.
	TraceFilterRule string `json:"traceFilterRule" yaml:"traceFilterRule"`

	// CtxHandler customizes a logger's behavior at runtime dynamically.
	CtxHandler CtxHandler `json:"-" yaml:"-"`
}

GlobalConfig configures some global behavior of this package.

type Level

type Level = zapcore.Level

Level is an alias type of zapcore.Level.

func GetLevel

func GetLevel() Level

GetLevel gets the global logging level.

type Logger

type Logger struct {
	*zap.Logger
	// contains filtered or unexported fields
}

Logger is a simple wrapper of *zap.Logger. It provides fast, leveled, structured logging. All methods are safe for concurrent use. A zero Logger is not ready to use, don't construct Logger instances outside this package.

func L

func L() Logger

L returns the global Logger, which can be reconfigured with SetupGlobals and ReplaceGlobals.

func With

func With(fields ...zap.Field) Logger

With creates a child logger and adds structured context to it. Fields added to the child don't affect the parent, and vice versa.

Example
defer testHelperReplaceGlobalsToStdout(nil)()

With(zap.String("k1", "v1"), zap.Int64("k2", 54321)).
	Info("example with")
Output:

{"level":"info","msg":"example with","k1":"v1","k2":54321}

func WithCtx

func WithCtx(ctx context.Context, extra ...zap.Field) Logger

WithCtx creates a child logger and customizes its behavior using context data (e.g. adding fields, dynamically changing level, etc.)

If ctx is created by WithLogger, it carries a logger instance, this function uses that logger as a base to create the child logger, else it calls Logger.Ctx to build the child logger with contextual fields and optional dynamic level from ctx.

Also see WithLogger, CtxHandler and CtxResult for more details.

Example
demoCtxFunc := func(ctx context.Context) CtxResult {
	return CtxResult{
		Fields: []zap.Field{zap.String("ctx1", "v1"), zap.Int64("ctx2", 123)},
	}
}
defer testHelperReplaceGlobalsToStdout(demoCtxFunc)()

logger := WithCtx(context.Background(),
	zap.String("k3", "v3"),         // add a new field
	zap.String("ctx2", "override"), // override "ctx2" from context
)
logger.Info("example with ctx")
Output:

{"level":"info","msg":"example with ctx","ctx1":"v1","ctx2":"override","k3":"v3"}

func (Logger) Ctx added in v2.13.0

func (l Logger) Ctx(ctx context.Context, extra ...zap.Field) Logger

Ctx creates a child logger, it calls CtxHandler.WithCtx to get CtxResult from ctx, adds CtxResult.Fields to the child logger and changes the logger's level to CtxResult.Level, if it is not nil.

func (Logger) Named added in v2.13.0

func (l Logger) Named(name string) Logger

Named adds a new path segment to the logger's name. Segments are joined by periods. By default, Loggers are unnamed.

func (Logger) Sugar added in v2.13.0

func (l Logger) Sugar() SugaredLogger

Sugar clones the current Logger, returns a SugaredLogger.

Sugaring a Logger is quite inexpensive, so it's reasonable for a single application to use both Loggers and SugaredLoggers, converting between them on the boundaries of performance-sensitive code.

func (Logger) Trace added in v2.13.0

func (l Logger) Trace(msg string, fields ...zap.Field)

Trace logs a message at TraceLevel if it's enabled.

If trace messages are disabled globally, calling this function is a no-op.

func (Logger) Tracef added in v2.13.0

func (l Logger) Tracef(format string, args ...any)

Tracef uses fmt.Sprintf to log a message at TraceLevel if it's enabled.

If trace messages are disabled globally, calling this function is a no-op.

func (Logger) With added in v2.13.0

func (l Logger) With(fields ...zap.Field) Logger

With creates a child logger and adds structured context to it. Fields added to the child don't affect the parent, and vice versa. Any fields that require evaluation (such as Objects) are evaluated upon invocation of With.

func (Logger) WithLazy added in v2.13.0

func (l Logger) WithLazy(fields ...zap.Field) Logger

WithLazy creates a child logger and adds structured context to it lazily.

The fields are evaluated only if the logger is further chained with With or is written to with any of the log level methods. Until that occurs, the logger may retain references to objects inside the fields, and logging will reflect the state of an object at the time of logging, not the time of WithLazy().

WithLazy provides a worthwhile performance optimization for contextual loggers when the likelihood of using the child logger is low, such as error paths and rarely taken branches.

Similar to With, fields added to the child don't affect the parent, and vice versa.

func (Logger) WithMethod added in v2.13.0

func (l Logger) WithMethod() Logger

WithMethod adds the caller's method name as a context field, using the globally configured GlobalConfig.MethodNameKey as key.

func (Logger) WithOptions added in v2.13.0

func (l Logger) WithOptions(opts ...zap.Option) Logger

WithOptions clones the current Logger, applies the supplied Options, and returns the resulting Logger. It's safe to use concurrently.

type LogrOptions added in v2.14.3

type LogrOptions struct {
	// Logger optionally configures a zap.Logger to use instead of
	// the default logger.
	Logger *zap.Logger

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

	// NumericLevelKey controls whether the numeric logr level is
	// added to each Info log message and the field key to use.
	NumericLevelKey string

	// DPanicOnInvalidLog 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, mismatched key-values pairs, etc.).
	// This is enabled by default.
	DPanicOnInvalidLog bool
}

LogrOptions customizes the behavior of logr logger created by NewLogrLogger.

type Properties

type Properties struct {
	// contains filtered or unexported fields
}

Properties holds some information about the global config and logger.

func New

func New(cfg *Config, opts ...zap.Option) (*zap.Logger, *Properties, error)

New initializes a zap logger.

If Config.File is configured, logs will be written to the specified file, and Config.PerLoggerFiles can be used to write logs to different files specified by logger name. By default, logs are written to stderr.

The returned zap.Logger supports dynamic level, see Config.PerLoggerLevels and GlobalConfig.CtxHandler for details about dynamic level. The returned zap.Logger and Properties may be passed to ReplaceGlobals to change the global logger and customize some global behavior of this package.

func NewWithCore

func NewWithCore(cfg *WrapCoreConfig, core zapcore.Core, opts ...zap.Option) (*zap.Logger, *Properties, error)

NewWithCore initializes a zap logger with given core.

You may use this function to integrate with custom cores (e.g. to integrate with Sentry or Graylog, or output to multiple sinks).

The returned zap.Logger supports dynamic level, see WrapCoreConfig.PerLoggerLevels and GlobalConfig.CtxHandler for details about dynamic level. Note that if you want to use the dynamic level feature, the provided core must be configured to log low level messages (e.g. debug).

The returned zap.Logger and Properties may be passed to ReplaceGlobals to change the global logger and customize some global behavior of this package.

func NewWithOutput

func NewWithOutput(cfg *Config, output zapcore.WriteSyncer, opts ...zap.Option) (*zap.Logger, *Properties, error)

NewWithOutput initializes a zap logger with given write syncer as output.

The returned zap.Logger supports dynamic level, see Config.PerLoggerLevels and GlobalConfig.CtxHandler for details about dynamic level. The returned zap.Logger and Properties may be passed to ReplaceGlobals to change the global logger and customize some global behavior of this package.

func (*Properties) CloseWriters added in v2.13.0

func (p *Properties) CloseWriters()

CloseWriters close all writers associated with this Properties object.

type ReplaceResult added in v2.14.3

type ReplaceResult struct {
	Field zapcore.Field
	Multi []zapcore.Field
}

ReplaceResult is a result returned by SlogOptions.ReplaceAttr. If there is only one field, set it to Field, else set multi fields to Multi. The logger checks both Field and Multi to append to result log.

Note that the field Multi must not contain values whose Type is UnknownType or SkipType.

type SlogOptions added in v2.14.3

type SlogOptions struct {
	// Logger optionally configures a zap.Logger to use instead of
	// the default logger.
	Logger *zap.Logger

	// DisableCaller stops annotating logs with calling function's file
	// name and line number. By default, all logs are annotated.
	DisableCaller bool

	// ReplaceAttr is called to rewrite an attribute before it is logged.
	// The attribute's value has been resolved (see [slog.Value.Resolve]).
	// If ReplaceAttr returns a zero ReplaceResult, the attribute is discarded.
	//
	// ReplaceAttr may return a single field by ReplaceResult.Field, or return
	// multi fields by ReplaceResult.Multi.
	// User may use this option to check error attribute and convert to a
	// zap.Error field to unify the key for errors, if the error contains
	// stack information, the function can also get it and add the
	// stacktrace to log.
	//
	// Note, for simplicity and better performance, it is different with
	// [slog.HandlerOptions.ReplaceAttr], only attributes directly passed to
	// [slog.Logger.With] and the log methods
	// (such as [slog.Logger.Log], [slog.Logger.Info], etc.)
	// are passed to this function, the builtin attributes and nested attributes
	// in groups are not.
	// The first argument is a list of currently open groups that added by
	// [slog.Logger.WithGroup].
	ReplaceAttr func(groups []string, a slog.Attr) (rr ReplaceResult)
}

SlogOptions customizes the behavior of slog logger created by NewSlogLogger.

type SugaredLogger added in v2.13.0

type SugaredLogger struct {
	*zap.SugaredLogger
	// contains filtered or unexported fields
}

SugaredLogger is a simple wrapper of *zap.SugaredLogger. It provides a slower, but less verbose, API. A zero SugaredLogger is not ready to use, don't construct SugaredLogger instances outside this package.

Any Logger can be converted to a SugaredLogger with its Sugar method.

func S

func S() SugaredLogger

S returns the global SugaredLogger, which can be reconfigured with SetupGlobals and ReplaceGlobals.

func SugaredWith added in v2.14.3

func SugaredWith(args ...any) SugaredLogger

SugaredWith creates a child logger and adds a variadic number of fields to the logging context. Fields added to the child don't affect the parent, and vice versa.

It accepts a mix of strongly-typed Field objects and loosely-typed key-value pairs. When processing pairs, the first element of the pair is used as the field key and the second as the field value.

func (SugaredLogger) Ctx added in v2.13.0

func (s SugaredLogger) Ctx(ctx context.Context, extra ...zap.Field) SugaredLogger

Ctx creates a child logger, it calls CtxHandler.WithCtx to get CtxResult from ctx, adds CtxResult.Fields to the child logger and changes the logger's level to CtxResult.Level, if it is not nil.

func (SugaredLogger) Desugar added in v2.13.0

func (s SugaredLogger) Desugar() Logger

Desugar unwraps a SugaredLogger, returning the original Logger.

Desugaring is quite inexpensive, so it's reasonable for a single application to use both Loggers and SugaredLoggers, converting between them on the boundaries of performance-sensitive code.

func (SugaredLogger) Named added in v2.13.0

func (s SugaredLogger) Named(name string) SugaredLogger

Named adds a sub-scope to the logger's name. See Logger.Named for details.

func (SugaredLogger) Tracef added in v2.13.0

func (s SugaredLogger) Tracef(format string, args ...any)

Tracef uses fmt.Sprintf to log a message at TraceLevel if it's enabled.

If trace messages are disabled globally, calling this function is a no-op.

func (SugaredLogger) With added in v2.13.0

func (s SugaredLogger) With(args ...any) SugaredLogger

With adds a variadic number of fields to the logging context. It accepts a mix of strongly-typed Field objects and loosely-typed key-value pairs. When processing pairs, the first element of the pair is used as the field key and the second as the field value.

Note that the keys in key-value pairs should be strings. In development, passing a non-string key panics. In production, the logger is more forgiving: a separate error is logged, but the key-value pair is skipped and execution continues. Passing an orphaned key triggers similar behavior: panics in development and errors in production.

func (SugaredLogger) WithMethod added in v2.13.0

func (s SugaredLogger) WithMethod() SugaredLogger

WithMethod adds the caller's method name as a context field, using the globally configured GlobalConfig.MethodNameKey as key.

func (SugaredLogger) WithOptions added in v2.13.0

func (s SugaredLogger) WithOptions(opts ...zap.Option) SugaredLogger

WithOptions clones the current SugaredLogger, applies the supplied Options, and returns the result. It's safe to use concurrently.

type Underlier added in v2.7.0

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.

type WrapCoreConfig

type WrapCoreConfig struct {
	// Level sets the default logging level for the logger.
	Level Level `json:"level" yaml:"level"`

	// PerLoggerLevels optionally configures logging level by logger names.
	// The format is "loggerName.subLogger=level".
	// If a level is configured for a parent logger, but not configured for
	// a child logger, the child logger will derive the level from its parent.
	PerLoggerLevels []string `json:"perLoggerLevels" yaml:"perLoggerLevels"`

	// Hooks registers functions which will be called each time the logger
	// writes out an Entry. Repeated use of Hooks is additive.
	//
	// This offers users an easy way to register simple callbacks (e.g.,
	// metrics collection) without implementing the full Core interface.
	//
	// See zap.Hooks and zapcore.RegisterHooks for details.
	Hooks []func(zapcore.Entry) error `json:"-" yaml:"-"`

	// GlobalConfig configures some global behavior of this package.
	// It works with SetupGlobals and ReplaceGlobals, it has no effect for
	// individual non-global loggers.
	GlobalConfig `yaml:",inline"`
}

Jump to

Keyboard shortcuts

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