Documentation ¶
Index ¶
- Constants
- Variables
- func DPanic(msg string, fields ...zap.Field)
- func DPanicf(format string, args ...interface{})
- func Debug(msg string, fields ...zap.Field)
- func Debugf(format string, args ...interface{})
- func Error(msg string, fields ...zap.Field)
- func Errorf(format string, args ...interface{})
- func Fatal(msg string, fields ...zap.Field)
- func Fatalf(format string, args ...interface{})
- func Info(msg string, fields ...zap.Field)
- func Infof(format string, args ...interface{})
- func L() *zap.Logger
- func Named(name string, extra ...zap.Field) *zap.Logger
- func NewLogfmtEncoder(cfg zapcore.EncoderConfig) zapcore.Encoder
- func Panic(msg string, fields ...zap.Field)
- func Panicf(format string, args ...interface{})
- func Print(args ...interface{})
- func Printf(format string, args ...interface{})
- func ReplaceGlobals(logger *zap.Logger, props *Properties) func()
- func S() *zap.SugaredLogger
- func SetDevelopment()
- func SetLevel(lvl Level)
- func SetupGlobals(cfg *Config, opts ...zap.Option)
- func Sync() error
- func TRACE(args ...interface{})
- func TRACESkip(skip int, args ...interface{})
- func Trace(msg string, fields ...zap.Field)
- func Tracef(format string, args ...interface{})
- func Warn(msg string, fields ...zap.Field)
- func Warnf(format string, args ...interface{})
- func With(fields ...zap.Field) *zap.Logger
- func WithBuilder(ctx context.Context, builder *Builder) context.Context
- func WithCtx(ctx context.Context, extra ...zap.Field) *zap.Logger
- func WithMethod(extra ...zap.Field) *zap.Logger
- type Builder
- func (b *Builder) Base(logger *zap.Logger) *Builder
- func (b *Builder) Build() *zap.Logger
- func (b *Builder) Ctx(ctx context.Context) *Builder
- func (b *Builder) Level(level Level) *Builder
- func (b *Builder) Method() *Builder
- func (b *Builder) Named(name string) *Builder
- func (b *Builder) Sugar() *zap.SugaredLogger
- func (b *Builder) With(fields ...zap.Field) *Builder
- type Config
- type CtxArgs
- type CtxFunc
- type CtxResult
- type FileLogConfig
- type GlobalConfig
- type Level
- type Logger
- type Properties
- func New(cfg *Config, opts ...zap.Option) (*zap.Logger, *Properties, error)
- func NewWithCore(cfg *WrapCoreConfig, core zapcore.Core, opts ...zap.Option) (*zap.Logger, *Properties, error)
- func NewWithOutput(cfg *Config, output zapcore.WriteSyncer, opts ...zap.Option) (*zap.Logger, *Properties, error)
- type WrapCoreConfig
Examples ¶
Constants ¶
const ( TracePrefix = "[TRACE] " DebugPrefix = "[DEBUG] " InfoPrefix = "[INFO] " NoticePrefix = "[NOTICE] " WarnPrefix = "[WARN] " ErrorPrefix = "[ERROR] " CriticalPrefix = "[CRITICAL] " PanicPrefix = "[PANIC] " FatalPrefix = "[FATAL] " )
Variables ¶
var ErrUnsupportedValueType = errors.New("unsupported value type")
Functions ¶
func L ¶
L returns the global Logger, which can be reconfigured with SetupGlobals and ReplaceGlobals.
func Named ¶
Named creates a child logger and adds a new name segment to the logger's name. By default, loggers are unnamed. It also adds the given extra fields to the logger.
func NewLogfmtEncoder ¶
func NewLogfmtEncoder(cfg zapcore.EncoderConfig) zapcore.Encoder
func Print ¶
func Print(args ...interface{})
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 ...interface{})
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 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 should be called at program startup, library code shall not touch this function.
func S ¶
func S() *zap.SugaredLogger
S returns the global SugaredLogger, which can be reconfigured with SetupGlobals and ReplaceGlobals.
func SetDevelopment ¶
func SetDevelopment()
SetDevelopment 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 should only 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 SetupGlobals ¶
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 should be called at program startup, library code shall not touch this function.
func TRACE ¶
func TRACE(args ...interface{})
TRACE logs a message at TraceLevel if it's enabled. It also adds a prefix "TRACE " to the message.
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 by GlobalConfig, calling this function is a no-op.
func TRACESkip ¶
func TRACESkip(skip int, args ...interface{})
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 by GlobalConfig, calling this function is a no-op.
func Trace ¶
Trace logs a message at TraceLevel if it's enabled. It also adds a prefix "TRACE " to the message.
If trace messages are disabled by GlobalConfig, calling this function is a no-op.
func Tracef ¶
func Tracef(format string, args ...interface{})
Tracef uses fmt.Sprintf to log a message at TraceLevel if it's enabled. It also adds a prefix "TRACE " to the message.
If trace messages are disabled by GlobalConfig, calling this function is a no-op.
func With ¶
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 WithBuilder ¶
WithBuilder returns a copy of parent ctx with builder associated. The associated builder can be accessed by B or WithCtx.
Example ¶
defer testHelperReplaceGlobalsToStdout(nil)() // Make a Builder. builder := B(context.TODO()). Method(). With(zap.String("k1", "v1"), zap.Int64("k2", 54321)) builder.Build().Info("with builder") // Pass it to another function or goroutine. ctx := WithBuilder(context.Background(), builder) func(ctx context.Context) { builder := B(ctx). // get Builder from ctx Method(). // override the method name With(zap.String("k1", "inner")) // override "k1" // do something builder.Build().Info("another function") }(ctx)
Output: {"level":"info","msg":"with builder","methodName":"zlog.ExampleWithBuilder","k1":"v1","k2":54321} {"level":"info","msg":"another function","methodName":"zlog.ExampleWithBuilder.func1","k1":"inner","k2":54321}
func WithCtx ¶
WithCtx creates a child logger and customizes its behavior using context data (e.g. adding fields, dynamically change logging level, etc.)
If the ctx is created by WithBuilder, it carries a Builder instance, this function uses that Builder to build the logger, else it calls GlobalConfig.CtxFunc to get CtxResult from ctx. In case that GlobalConfig.CtxFunc is not configured globally, it logs an error message at DPANIC level.
Also see GlobalConfig.CtxFunc, CtxArgs and CtxResult for more details.
Example ¶
demoCtxFunc := func(ctx context.Context, args CtxArgs) 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"}
Types ¶
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder provides chaining methods to build a logger. Different with calling zap.Logger's methods, it does not write the context information to underlying buffer immediately, later data will override the former which has same key within a namespace. When the builder is prepared, call Build to get the final logger.
A Builder is safe for concurrent use, it will copy data if necessary. User may pass a Builder across functions to handle duplicate.
A zero value for Builder is ready to use. A Builder must not be copied after first use.
Example ¶
defer testHelperReplaceGlobalsToStdout(nil)() logger := B(context.TODO()). Named("example_builder"). Method(). With(zap.String("k1", "v1"), zap.Int64("k2", 54321)). Build() logger.Info("example builder")
Output: {"level":"info","logger":"example_builder","msg":"example builder","methodName":"zlog.ExampleBuilder","k1":"v1","k2":54321}
Example (Namespace) ¶
defer testHelperReplaceGlobalsToStdout(nil)() builder := B(nil). With(zap.String("k1", "v1"), zap.String("k2", "v2")). With(zap.Namespace("subns")) builder = builder.With(zap.String("k1", "sub1"), zap.String("k2", "sub2")) builder.Build().Info("example builder namespace")
Output: {"level":"info","msg":"example builder namespace","k1":"v1","k2":"v2","subns":{"k1":"sub1","k2":"sub2"}}
Example (NewNamespace) ¶
defer testHelperReplaceGlobalsToStdout(nil)() builder := B(nil) builder = builder.With(zap.String("k1", "v1"), zap.String("k2", "v2")) builder = builder.With( zap.String("k1", "override"), zap.Namespace("subns"), zap.String("k1", "sub1"), zap.String("k2", "sub2")) builder.Build().Info("example builder new namespace")
Output: {"level":"info","msg":"example builder new namespace","k1":"override","k2":"v2","subns":{"k1":"sub1","k2":"sub2"}}
func B ¶
B returns a Builder with given ctx.
If ctx is nil, it returns an empty Builder, else if the ctx is created by WithBuilder, then it carries a Builder instance, this function returns that Builder. Otherwise, if the ctx is not nil and GlobalConfig.CtxFunc is configured globally, it calls the CtxFunc to get CtxResult from ctx.
func (*Builder) Ctx ¶
Ctx customizes the logger's behavior using context data (e.g. adding fields, dynamically change logging level, etc.) See GlobalConfig.CtxFunc, CtxArgs and CtxResult for details.
It calls GlobalConfig.CtxFunc to get CtxResult from ctx, in case that GlobalConfig.CtxFunc is not configured globally, it logs an error message at DPANIC level.
func (*Builder) Level ¶
Level optionally changes the level of a logger. By default, a child logger has same level with its parent.
func (*Builder) Named ¶
Named adds a new path segment to the logger's name. By default, loggers are unnamed.
func (*Builder) Sugar ¶
func (b *Builder) Sugar() *zap.SugaredLogger
Sugar builds and returns the final sugared logger. It's a shortcut for Builder.Build().Sugar()
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 will derive the level 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 FileLogConfig `json:"file" yaml:"file"` // 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 stacktraces 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 WarnLevel and above logs in // development and ErrorLevel and above in production. 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 // non-global individual loggers. GlobalConfig `yaml:",inline"` }
Config serializes log related config in json/yaml.
type CtxFunc ¶
CtxFunc gets additional logging data from ctx, it may return extra fields to attach to the logging entry, or change the logging level dynamically.
type CtxResult ¶
type CtxResult struct { // Fields will be added to the logger as additional fields. Fields []zap.Field // An optional Level can be used to dynamically change the logging level. Level *Level }
CtxResult holds values returned by Config.CtxFunc, which will be used to customize a logger's behavior.
type FileLogConfig ¶
type FileLogConfig 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 300 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. 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. MaxBackups int `json:"maxBackups" yaml:"maxBackups"` }
FileLogConfig serializes file log related config in json/yaml.
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"` // DisableTrace disables trace level messages. // // Disabling trace level messages makes the trace logging functions no-op, // it gives better performance when you definitely don't need TraceLevel // messages (e.g. in production deployment). DisableTrace bool `json:"disableTrace" yaml:"disableTrace"` // 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"` // CtxFunc gets additional logging information from ctx, it's optional. // // See also CtxArgs, CtxResult, WithCtx and Builder.Ctx. CtxFunc CtxFunc `json:"-" yaml:"-"` }
GlobalConfig configures some global behavior of this package.
type Level ¶
type Level int8
A Level is a logging priority. Higher levels are more important.
const ( // TraceLevel logs are the most fine-grained information which helps // developer "tracing" the code and trying to find one part of a // function specifically. Use this level when you need full visibility // of what is happening in your application and inside the third-party // libraries that you use. // // You can expect this logging level to be very verbose. You can use it // for example to annotate each step in the algorithm or each individual // query with parameters in your code. TraceLevel Level = iota - 2 // DebugLevel logs are less granular compared to TraceLevel, but it is // more than you will need in everyday use. DebugLevel should be used // for information that may be needed for diagnosing issues and // troubleshooting or when running application in development or test // environment for the purpose of making sure everything is running // correctly. // // DebugLevel logs are helpful for diagnosing and troubleshooting to // people more than just developers (e.g. IT, system admins, etc.). DebugLevel // InfoLevel logs are generally useful information which indicate that // something happened, the application entered a certain state, etc. // For example, a controller of your authorization API may write a // message at InfoLevel with information on which user requested // authorization if the authorization was successful or not. // // The information logged at InfoLevel should be purely informative // that you don't need to care about under normal circumstances, and // not looking into them on a regular basis shouldn't result in missing // any important information. // // This should be the out-of-box level for most applications in // service production deployment or application release configuration. InfoLevel // NoticeLevel logs are important information which should be always // available and shall not be turned off, user should be aware of these // events when they look into the system or application. // (Such as service start/stop/restart, reconnecting to database, switching // from a primary server to a backup server, retrying an operation, etc.) // // NoticeLevel is not implemented currently. NoticeLevel // WarnLevel logs indicate that something unexpected happened in the // system or application, a problem, or a situation that might // potentially cause application oddities, but the code can continue // to work. For example, unexpected disconnection from server, being // close to quota, suspicious web attach, temporarily heartbeat missing, // or a parsing error that resulted in a certain document not being // correctly processed. // // Warning messages may need human review, but generally that don't need // immediately intervention. WarnLevel // ErrorLevel logs indicate that the application hit issues preventing // one or more functionalities from properly functioning, they may be // fatal to an operation, but not fatal to the entire service or // application (e.g. can't open a required file, missing data, // temporarily failure from database or downstream service, etc.), // the application should continue running. // // These messages definitely need investigation and intervention from // user (developer, system administrator, or direct user), continuous // errors may cause serious problems, (e.g. service outage, lost of // income, or customer complaints, etc.). ErrorLevel // CriticalLevel logs indicate that the system or application encountered // critical condition preventing it to function properly, the system // or application is in a very unhealthy state. // // Intervention actions must be taken immediately, which means you should // go to get a system administrator or developer out of bed quickly. // // CriticalLevel is not implemented currently. CriticalLevel // DPanicLevel logs are particularly important errors. // In development mode the logger panics after writing the message. DPanicLevel // PanicLevel logs indicate that the application encountered unrecoverable // errors that it should abort immediately. // // The logger writes the message, then panics the application. PanicLevel // FatalLevel logs indicate that the application encountered unrecoverable // errors that it should abort immediately. // // The logger writes the message, then calls os.Exit to abort the application. FatalLevel )
func (Level) CapitalString ¶
type Logger ¶
type Logger interface { Debugf(format string, args ...interface{}) Infof(format string, args ...interface{}) Warnf(format string, args ...interface{}) Errorf(format string, args ...interface{}) Fatalf(format string, args ...interface{}) }
Logger is a generic logger interface that output logs with a format. It's implemented by many logging libraries, including logrus.Logger, zap.SugaredLogger, etc.
Within this package, StdLogger is a default implementation which sends log messages to the standard library, it also adds the level prefix to the output message.
var NopLogger Logger = &nopLogger{}
NopLogger is a logger which discards anything it receives.
var StdLogger Logger = stdLogger{}
StdLogger is a default implementation of Logger which sends log messages to the standard library.
It follows the global logging level of this package, the level can be changed by calling SetLevel.
type Properties ¶
type Properties struct {
// contains filtered or unexported fields
}
Properties records some information about the global config.
func New ¶
New initializes a zap logger.
If Config.File is configured, the log messages will be written to the specified file with rotation, else they will be written to stderr.
The returned zap.Logger supports dynamic level, see Config.PerLoggerLevels and GlobalConfig.CtxFunc 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.CtxFunc 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 destination.
The returned zap.Logger supports dynamic level, see Config.PerLoggerLevels and GlobalConfig.CtxFunc 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) GetLevel ¶
func (p *Properties) GetLevel() Level
GetLevel gets the logging level of the logger.
func (*Properties) SetLevel ¶
func (p *Properties) SetLevel(lvl Level)
SetLevel modifies the logging level of the logger.
type WrapCoreConfig ¶
type WrapCoreConfig struct { // Level sets the default logging level for the logger. Level 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 // 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 // GlobalConfig configures some global behavior of this package. // It works with SetupGlobals and ReplaceGlobals, it has no effect for // non-global individual loggers. GlobalConfig `yaml:",inline"` }