Documentation ¶
Index ¶
- Constants
- func CombineWriteSyncers(writers ...core.WriteSyncer) core.WriteSyncer
- func LevelFlag(name string, defaultLevel core.Level, usage string) *core.Level
- func NewDevelopmentEncoderConfig() core.EncoderConfig
- func NewProductionEncoderConfig() core.EncoderConfig
- func NewStdLog(l *Logger) *log.Logger
- func NewStdLogAt(l *Logger, level core.Level) (*log.Logger, error)
- func Open(paths ...string) (core.WriteSyncer, func(), error)
- func RedirectStdLog(l *Logger) func()
- func RedirectStdLogAt(l *Logger, level core.Level) (func(), error)
- func RegisterEncoder(name string, constructor func(core.EncoderConfig) (core.Encoder, error)) error
- func RegisterSink(scheme string, factory func(*url.URL) (Sink, error)) error
- func ReplaceGlobals(logger *Logger) func()
- type AtomicLevel
- func (lvl AtomicLevel) Enabled(l core.Level) bool
- func (lvl AtomicLevel) Level() core.Level
- func (lvl AtomicLevel) MarshalText() (text []byte, err error)
- func (lvl AtomicLevel) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (lvl AtomicLevel) SetLevel(l core.Level)
- func (lvl AtomicLevel) String() string
- func (lvl *AtomicLevel) UnmarshalText(text []byte) error
- type Config
- type Field
- func Any(key string, value interface{}) Field
- func Array(key string, val core.ArrayMarshaler) Field
- func Binary(key string, val []byte) Field
- func Bool(key string, val bool) Field
- func Boolp(key string, val *bool) Field
- func Bools(key string, bs []bool) Field
- func ByteString(key string, val []byte) Field
- func ByteStrings(key string, bss [][]byte) Field
- func Complex128(key string, val complex128) Field
- func Complex128p(key string, val *complex128) Field
- func Complex128s(key string, nums []complex128) Field
- func Complex64(key string, val complex64) Field
- func Complex64p(key string, val *complex64) Field
- func Complex64s(key string, nums []complex64) Field
- func Duration(key string, val time.Duration) Field
- func Durationp(key string, val *time.Duration) Field
- func Durations(key string, ds []time.Duration) Field
- func Error(err error) Field
- func Errors(key string, errs []error) Field
- func Float32(key string, val float32) Field
- func Float32p(key string, val *float32) Field
- func Float32s(key string, nums []float32) Field
- func Float64(key string, val float64) Field
- func Float64p(key string, val *float64) Field
- func Float64s(key string, nums []float64) Field
- func Inline(val core.ObjectMarshaler) Field
- func Int(key string, val int) Field
- func Int16(key string, val int16) Field
- func Int16p(key string, val *int16) Field
- func Int16s(key string, nums []int16) Field
- func Int32(key string, val int32) Field
- func Int32p(key string, val *int32) Field
- func Int32s(key string, nums []int32) Field
- func Int64(key string, val int64) Field
- func Int64p(key string, val *int64) Field
- func Int64s(key string, nums []int64) Field
- func Int8(key string, val int8) Field
- func Int8p(key string, val *int8) Field
- func Int8s(key string, nums []int8) Field
- func Intp(key string, val *int) Field
- func Ints(key string, nums []int) Field
- func NamedError(key string, err error) Field
- func Namespace(key string) Field
- func Object(key string, val core.ObjectMarshaler) Field
- func Reflect(key string, val interface{}) Field
- func Skip() Field
- func Stack(key string) Field
- func StackSkip(key string, skip int) Field
- func String(key string, val string) Field
- func Stringer(key string, val fmt.Stringer) Field
- func Stringp(key string, val *string) Field
- func Strings(key string, ss []string) Field
- func Time(key string, val time.Time) Field
- func Timep(key string, val *time.Time) Field
- func Times(key string, ts []time.Time) Field
- func Uint(key string, val uint) Field
- func Uint16(key string, val uint16) Field
- func Uint16p(key string, val *uint16) Field
- func Uint16s(key string, nums []uint16) Field
- func Uint32(key string, val uint32) Field
- func Uint32p(key string, val *uint32) Field
- func Uint32s(key string, nums []uint32) Field
- func Uint64(key string, val uint64) Field
- func Uint64p(key string, val *uint64) Field
- func Uint64s(key string, nums []uint64) Field
- func Uint8(key string, val uint8) Field
- func Uint8p(key string, val *uint8) Field
- func Uint8s(key string, nums []uint8) Field
- func Uintp(key string, val *uint) Field
- func Uintptr(key string, val uintptr) Field
- func Uintptrp(key string, val *uintptr) Field
- func Uintptrs(key string, us []uintptr) Field
- func Uints(key string, nums []uint) Field
- type LevelEnablerFunc
- type Log
- type LogConfig
- type Logger
- func (log *Logger) Check(lvl core.Level, msg string) *core.CheckedEntry
- func (log *Logger) Core() core.Core
- func (log *Logger) DPanic(msg string, fields ...Field)
- func (log *Logger) Debug(msg string, fields ...Field)
- func (log *Logger) Error(msg string, fields ...Field)
- func (log *Logger) Fatal(msg string, fields ...Field)
- func (log *Logger) Info(msg string, fields ...Field)
- func (log *Logger) Named(s string) *Logger
- func (log *Logger) Panic(msg string, fields ...Field)
- func (log *Logger) Sugar() *SugaredLogger
- func (log *Logger) Sync() error
- func (log *Logger) Warn(msg string, fields ...Field)
- func (log *Logger) With(fields ...Field) *Logger
- func (log *Logger) WithOptions(opts ...Option) *Logger
- type Option
- func AddCaller() Option
- func AddCallerSkip(skip int) Option
- func AddStacktrace(lvl core.LevelEnabler) Option
- func Development() Option
- func ErrorOutput(w core.WriteSyncer) Option
- func Fields(fs ...Field) Option
- func Hooks(hooks ...func(core.Entry) error) Option
- func IncreaseLevel(lvl core.LevelEnabler) Option
- func OnFatal(action core.CheckWriteAction) Option
- func WithCaller(enabled bool) Option
- func WithClock(clock core.Clock) Option
- func WrapCore(f func(core.Core) core.Core) Option
- type SamplingConfig
- type Sink
- type SugaredLogger
- func (s *SugaredLogger) DPanic(args ...interface{})
- func (s *SugaredLogger) DPanicf(template string, args ...interface{})
- func (s *SugaredLogger) DPanicw(msg string, keysAndValues ...interface{})
- func (s *SugaredLogger) Debug(args ...interface{})
- func (s *SugaredLogger) Debugf(template string, args ...interface{})
- func (s *SugaredLogger) Debugw(msg string, keysAndValues ...interface{})
- func (s *SugaredLogger) Desugar() *Logger
- func (s *SugaredLogger) Error(args ...interface{})
- func (s *SugaredLogger) Errorf(template string, args ...interface{})
- func (s *SugaredLogger) Errorw(msg string, keysAndValues ...interface{})
- func (s *SugaredLogger) Fatal(args ...interface{})
- func (s *SugaredLogger) Fatalf(template string, args ...interface{})
- func (s *SugaredLogger) Fatalw(msg string, keysAndValues ...interface{})
- func (s *SugaredLogger) Info(args ...interface{})
- func (s *SugaredLogger) Infof(template string, args ...interface{})
- func (s *SugaredLogger) Infow(msg string, keysAndValues ...interface{})
- func (s *SugaredLogger) Named(name string) *SugaredLogger
- func (s *SugaredLogger) Panic(args ...interface{})
- func (s *SugaredLogger) Panicf(template string, args ...interface{})
- func (s *SugaredLogger) Panicw(msg string, keysAndValues ...interface{})
- func (s *SugaredLogger) Sync() error
- func (s *SugaredLogger) Warn(args ...interface{})
- func (s *SugaredLogger) Warnf(template string, args ...interface{})
- func (s *SugaredLogger) Warnw(msg string, keysAndValues ...interface{})
- func (s *SugaredLogger) With(args ...interface{}) *SugaredLogger
Constants ¶
const ( // DebugLevel logs are typically voluminous, and are usually disabled in // production. DebugLevel = core.DebugLevel // InfoLevel is the default logging priority. InfoLevel = core.InfoLevel // WarnLevel logs are more important than Info, but don't need individual // human review. WarnLevel = core.WarnLevel // ErrorLevel logs are high-priority. If an application is running smoothly, // it shouldn't generate any error-level logs. ErrorLevel = core.ErrorLevel // DPanicLevel logs are particularly important errors. In development the // logger panics after writing the message. DPanicLevel = core.DPanicLevel // PanicLevel logs a message, then panics. PanicLevel = core.PanicLevel // FatalLevel logs a message, then calls os.Exit(1). FatalLevel = core.FatalLevel )
Variables ¶
This section is empty.
Functions ¶
func CombineWriteSyncers ¶ added in v1.3.8
func CombineWriteSyncers(writers ...core.WriteSyncer) core.WriteSyncer
CombineWriteSyncers is a utility that combines multiple WriteSyncers into a single, locked WriteSyncer. If no inputs are supplied, it returns a no-op WriteSyncer.
It's provided purely as a convenience; the result is no different from using core.NewMultiWriteSyncer and core.Lock individually.
func LevelFlag ¶ added in v1.3.8
LevelFlag uses the standard library's flag.Var to declare a global flag with the specified name, default, and usage guidance. The returned value is a pointer to the value of the flag.
If you don't want to use the flag package's global state, you can use any non-nil *Level as a flag.Value with your own *flag.FlagSet.
func NewDevelopmentEncoderConfig ¶ added in v1.3.8
func NewDevelopmentEncoderConfig() core.EncoderConfig
NewDevelopmentEncoderConfig returns an opinionated EncoderConfig for development environments.
func NewProductionEncoderConfig ¶ added in v1.3.8
func NewProductionEncoderConfig() core.EncoderConfig
NewProductionEncoderConfig returns an opinionated EncoderConfig for production environments.
func NewStdLogAt ¶ added in v1.3.8
NewStdLogAt 使用指定的日志界别创建日志对象
func Open ¶ added in v1.3.8
func Open(paths ...string) (core.WriteSyncer, func(), error)
Open is a high-level wrapper that takes a variadic number of URLs, opens or creates each of the specified resources, and combines them into a locked WriteSyncer. It also returns any error encountered and a function to close any opened files.
Passing no URLs returns a no-op WriteSyncer. Zap handles URLs without a scheme and URLs with the "file" scheme. Third-party code may register factories for other schemes using RegisterSink.
URLs with the "file" scheme must use absolute paths on the local filesystem. No user, password, port, fragments, or query parameters are allowed, and the hostname must be empty or "localhost".
Since it's common to write logs to the local filesystem, URLs without a scheme (e.g., "/var/log/foo.log") are treated as local file paths. Without a scheme, the special paths "stdout" and "stderr" are interpreted as os.Stdout and os.Stderr. When specified without a scheme, relative file paths also work.
func RedirectStdLog ¶ added in v1.3.8
func RedirectStdLog(l *Logger) func()
RedirectStdLog 将标准库的包全局记录器的输出重定向到info level提供的记录器。 因为zap已经处理了调用者注解、时间戳等,所以它会自动禁用标准库的注解和前缀。 它返回一个函数来恢复原来的前缀和标志,并将标准库的输出重置为os.Stderr。
func RedirectStdLogAt ¶ added in v1.3.8
RedirectStdLogAt 将输出从标准库的包全局记录器重定向到指定级别上提供的记录器。 因为zap已经处理了调用者注解、时间戳等,所以它会自动禁用标准库的注解和前缀。 它返回一个函数来恢复原来的前缀和标志,并将标准库的输出重置为os.Stderr。
func RegisterEncoder ¶ added in v1.3.8
RegisterEncoder registers an encoder constructor, which the Config struct can then reference. By default, the "json" and "console" encoders are registered.
Attempting to register an encoder whose name is already taken returns an error.
func RegisterSink ¶ added in v1.3.8
RegisterSink registers a user-supplied factory for all sinks with a particular scheme.
All schemes must be ASCII, valid under section 3.1 of RFC 3986 (https://tools.ietf.org/html/rfc3986#section-3.1), and must not already have a factory registered. Zap automatically registers a factory for the "file" scheme.
func ReplaceGlobals ¶ added in v1.3.8
func ReplaceGlobals(logger *Logger) func()
ReplaceGlobals 替换全局的Logger和SugaredLogger对象,返回一个函数,执行该函数会恢复之前的全局对象。这是线程安全的方法。
Types ¶
type AtomicLevel ¶ added in v1.3.8
type AtomicLevel struct {
// contains filtered or unexported fields
}
An AtomicLevel is an atomically changeable, dynamic logging level. It lets you safely change the log level of a tree of loggers (the root logger and any children created by adding context) at runtime.
The AtomicLevel itself is an http.Handler that serves a JSON endpoint to alter its level.
AtomicLevels must be created with the NewAtomicLevel constructor to allocate their internal atomic pointer.
func NewAtomicLevel ¶ added in v1.3.8
func NewAtomicLevel() AtomicLevel
NewAtomicLevel creates an AtomicLevel with InfoLevel and above logging enabled.
func NewAtomicLevelAt ¶ added in v1.3.8
func NewAtomicLevelAt(l core.Level) AtomicLevel
NewAtomicLevelAt is a convenience function that creates an AtomicLevel and then calls SetLevel with the given level.
func (AtomicLevel) Enabled ¶ added in v1.3.8
func (lvl AtomicLevel) Enabled(l core.Level) bool
Enabled implements the core.LevelEnabler interface, which allows the AtomicLevel to be used in place of traditional static levels.
func (AtomicLevel) Level ¶ added in v1.3.8
func (lvl AtomicLevel) Level() core.Level
Level returns the minimum enabled log level.
func (AtomicLevel) MarshalText ¶ added in v1.3.8
func (lvl AtomicLevel) MarshalText() (text []byte, err error)
MarshalText marshals the AtomicLevel to a byte slice. It uses the same text representation as the static core.Levels ("debug", "info", "warn", "error", "dpanic", "panic", and "fatal").
func (AtomicLevel) ServeHTTP ¶ added in v1.3.8
func (lvl AtomicLevel) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP is a simple JSON endpoint that can report on or change the current logging level.
GET ¶
The GET request returns a JSON description of the current logging level like:
{"level":"info"}
PUT ¶
The PUT request changes the logging level. It is perfectly safe to change the logging level while a program is running. Two content types are supported:
Content-Type: application/x-www-form-urlencoded
With this content type, the level can be provided through the request body or a query parameter. The log level is URL encoded like:
level=debug
The request body takes precedence over the query parameter, if both are specified.
This content type is the default for a curl PUT request. Following are two example curl requests that both set the logging level to debug.
curl -X PUT localhost:8080/log/level?level=debug curl -X PUT localhost:8080/log/level -d level=debug
For any other content type, the payload is expected to be JSON encoded and look like:
{"level":"info"}
An example curl request could look like this:
curl -X PUT localhost:8080/log/level -H "Content-Type: application/json" -d '{"level":"debug"}'
func (AtomicLevel) SetLevel ¶ added in v1.3.8
func (lvl AtomicLevel) SetLevel(l core.Level)
SetLevel alters the logging level.
func (AtomicLevel) String ¶ added in v1.3.8
func (lvl AtomicLevel) String() string
String returns the string representation of the underlying Level.
func (*AtomicLevel) UnmarshalText ¶ added in v1.3.8
func (lvl *AtomicLevel) UnmarshalText(text []byte) error
UnmarshalText unmarshals the text to an AtomicLevel. It uses the same text representations as the static core.Levels ("debug", "info", "warn", "error", "dpanic", "panic", and "fatal").
type Config ¶ added in v1.0.3
type Config struct { // Level is the minimum enabled logging level. Note that this is a dynamic // level, so calling Config.Level.SetLevel will atomically change the log // level of all loggers descended from this config. Level AtomicLevel `json:"level" yaml:"level"` // Development puts the logger in development mode, which changes the // behavior of DPanicLevel and takes stacktraces more liberally. Development bool `json:"development" yaml:"development"` // 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 completely disables automatic stacktrace capturing. By // default, stacktraces are captured for WarnLevel and above logs in // development and ErrorLevel and above in production. DisableStacktrace bool `json:"disableStacktrace" yaml:"disableStacktrace"` // Sampling sets a sampling policy. A nil SamplingConfig disables sampling. Sampling *SamplingConfig `json:"sampling" yaml:"sampling"` // Encoding sets the logger's encoding. Valid values are "json" and // "console", as well as any third-party encodings registered via // RegisterEncoder. Encoding string `json:"encoding" yaml:"encoding"` // EncoderConfig sets options for the chosen encoder. See // core.EncoderConfig for details. EncoderConfig core.EncoderConfig `json:"encoderConfig" yaml:"encoderConfig"` // OutputPaths is a list of URLs or file paths to write logging output to. // See Open for details. OutputPaths []string `json:"outputPaths" yaml:"outputPaths"` // ErrorOutputPaths is a list of URLs to write internal logger errors to. // The default is standard error. // // Note that this setting only affects internal errors; for sample code that // sends error-level logs to a different location from info- and debug-level // logs, see the package-level AdvancedConfiguration example. ErrorOutputPaths []string `json:"errorOutputPaths" yaml:"errorOutputPaths"` // InitialFields is a collection of fields to add to the root logger. InitialFields map[string]interface{} `json:"initialFields" yaml:"initialFields"` }
Config offers a declarative way to construct a logger. It doesn't do anything that can't be done with New, Options, and the various core.WriteSyncer and core.Core wrappers, but it's a simpler way to toggle common options.
Note that Config intentionally supports only the most common options. More unusual logging setups (logging to network connections or message queues, splitting output between multiple files, etc.) are possible, but require direct use of the core package. For sample code, see the package-level BasicConfiguration and AdvancedConfiguration examples.
For an example showing runtime log level changes, see the documentation for AtomicLevel.
func NewDevelopmentConfig ¶ added in v1.3.8
func NewDevelopmentConfig() Config
NewDevelopmentConfig is a reasonable development logging configuration. Logging is enabled at DebugLevel and above.
It enables development mode (which makes DPanicLevel logs panic), uses a console encoder, writes to standard error, and disables sampling. Stacktraces are automatically included on logs of WarnLevel and above.
func NewProductionConfig ¶ added in v1.3.8
func NewProductionConfig() Config
NewProductionConfig is a reasonable production logging configuration. Logging is enabled at InfoLevel and above.
It uses a JSON encoder, writes to standard error, and enables sampling. Stacktraces are automatically included on logs of ErrorLevel and above.
type Field ¶ added in v1.3.8
Field is an alias for Field. Aliasing this type dramatically improves the navigability of this package's API documentation.
func Any ¶ added in v1.3.8
Any takes a key and an arbitrary value and chooses the best way to represent them as a field, falling back to a reflection-based approach only if necessary.
Since byte/uint8 and rune/int32 are aliases, Any can't differentiate between them. To minimize surprises, []byte values are treated as binary blobs, byte values are treated as uint8, and runes are always treated as integers.
func Array ¶ added in v1.3.8
func Array(key string, val core.ArrayMarshaler) Field
Array constructs a field with the given key and ArrayMarshaler. It provides a flexible, but still type-safe and efficient, way to add array-like types to the logging context. The struct's MarshalLogArray method is called lazily.
func Binary ¶ added in v1.3.8
Binary constructs a field that carries an opaque binary blob.
Binary data is serialized in an encoding-appropriate format. For example, zap's JSON encoder base64-encodes binary blobs. To log UTF-8 encoded text, use ByteString.
func Boolp ¶ added in v1.3.8
Boolp constructs a field that carries a *bool. The returned Field will safely and explicitly represent `nil` when appropriate.
func ByteString ¶ added in v1.3.8
ByteString constructs a field that carries UTF-8 encoded text as a []byte. To log opaque binary blobs (which aren't necessarily valid UTF-8), use Binary.
func ByteStrings ¶ added in v1.3.8
ByteStrings constructs a field that carries a slice of []byte, each of which must be UTF-8 encoded text.
func Complex128 ¶ added in v1.3.8
func Complex128(key string, val complex128) Field
Complex128 constructs a field that carries a complex number. Unlike most numeric fields, this costs an allocation (to convert the complex128 to interface{}).
func Complex128p ¶ added in v1.3.8
func Complex128p(key string, val *complex128) Field
Complex128p constructs a field that carries a *complex128. The returned Field will safely and explicitly represent `nil` when appropriate.
func Complex128s ¶ added in v1.3.8
func Complex128s(key string, nums []complex128) Field
Complex128s constructs a field that carries a slice of complex numbers.
func Complex64 ¶ added in v1.3.8
Complex64 constructs a field that carries a complex number. Unlike most numeric fields, this costs an allocation (to convert the complex64 to interface{}).
func Complex64p ¶ added in v1.3.8
Complex64p constructs a field that carries a *complex64. The returned Field will safely and explicitly represent `nil` when appropriate.
func Complex64s ¶ added in v1.3.8
Complex64s constructs a field that carries a slice of complex numbers.
func Duration ¶ added in v1.3.8
Duration constructs a field with the given key and value. The encoder controls how the duration is serialized.
func Durationp ¶ added in v1.3.8
Durationp constructs a field that carries a *time.Duration. The returned Field will safely and explicitly represent `nil` when appropriate.
func Durations ¶ added in v1.3.8
Durations constructs a field that carries a slice of time.Durations.
func Float32 ¶ added in v1.3.8
Float32 constructs a field that carries a float32. The way the floating-point value is represented is encoder-dependent, so marshaling is necessarily lazy.
func Float32p ¶ added in v1.3.8
Float32p constructs a field that carries a *float32. The returned Field will safely and explicitly represent `nil` when appropriate.
func Float64 ¶ added in v1.3.8
Float64 constructs a field that carries a float64. The way the floating-point value is represented is encoder-dependent, so marshaling is necessarily lazy.
func Float64p ¶ added in v1.3.8
Float64p constructs a field that carries a *float64. The returned Field will safely and explicitly represent `nil` when appropriate.
func Inline ¶ added in v1.3.8
func Inline(val core.ObjectMarshaler) Field
Inline constructs a Field that is similar to Object, but it will add the elements of the provided ObjectMarshaler to the current namespace.
func Int16p ¶ added in v1.3.8
Int16p constructs a field that carries a *int16. The returned Field will safely and explicitly represent `nil` when appropriate.
func Int32p ¶ added in v1.3.8
Int32p constructs a field that carries a *int32. The returned Field will safely and explicitly represent `nil` when appropriate.
func Int64p ¶ added in v1.3.8
Int64p constructs a field that carries a *int64. The returned Field will safely and explicitly represent `nil` when appropriate.
func Int8p ¶ added in v1.3.8
Int8p constructs a field that carries a *int8. The returned Field will safely and explicitly represent `nil` when appropriate.
func Intp ¶ added in v1.3.8
Intp constructs a field that carries a *int. The returned Field will safely and explicitly represent `nil` when appropriate.
func NamedError ¶ added in v1.3.8
NamedError constructs a field that lazily stores err.Error() under the provided key. Errors which also implement fmt.Formatter (like those produced by github.com/pkg/errors) will also have their verbose representation stored under key+"Verbose". If passed a nil error, the field is a no-op.
For the common case in which the key is simply "error", the Error function is shorter and less repetitive.
func Namespace ¶ added in v1.3.8
Namespace creates a named, isolated scope within the logger's context. All subsequent fields will be added to the new namespace.
This helps prevent key collisions when injecting loggers into sub-components or third-party libraries.
func Object ¶ added in v1.3.8
func Object(key string, val core.ObjectMarshaler) Field
Object constructs a field with the given key and ObjectMarshaler. It provides a flexible, but still type-safe and efficient, way to add map- or struct-like user-defined types to the logging context. The struct's MarshalLogObject method is called lazily.
func Reflect ¶ added in v1.3.8
Reflect constructs a field with the given key and an arbitrary object. It uses an encoding-appropriate, reflection-based function to lazily serialize nearly any object into the logging context, but it's relatively slow and allocation-heavy. Outside tests, Any is always a better choice.
If encoding fails (e.g., trying to serialize a map[int]string to JSON), Reflect includes the error message in the final log output.
func Skip ¶ added in v1.3.8
func Skip() Field
Skip constructs a no-op field, which is often useful when handling invalid inputs in other Field constructors.
func Stack ¶ added in v1.3.8
Stack constructs a field that stores a stacktrace of the current goroutine under provided key. Keep in mind that taking a stacktrace is eager and expensive (relatively speaking); this function both makes an allocation and takes about two microseconds.
func StackSkip ¶ added in v1.3.8
StackSkip constructs a field similarly to Stack, but also skips the given number of frames from the top of the stacktrace.
func Stringer ¶ added in v1.3.8
Stringer constructs a field with the given key and the output of the value's String method. The Stringer's String method is called lazily.
func Stringp ¶ added in v1.3.8
Stringp constructs a field that carries a *string. The returned Field will safely and explicitly represent `nil` when appropriate.
func Time ¶ added in v1.3.8
Time constructs a Field with the given key and value. The encoder controls how the time is serialized.
func Timep ¶ added in v1.3.8
Timep constructs a field that carries a *time.Time. The returned Field will safely and explicitly represent `nil` when appropriate.
func Uint16p ¶ added in v1.3.8
Uint16p constructs a field that carries a *uint16. The returned Field will safely and explicitly represent `nil` when appropriate.
func Uint16s ¶ added in v1.3.8
Uint16s constructs a field that carries a slice of unsigned integers.
func Uint32p ¶ added in v1.3.8
Uint32p constructs a field that carries a *uint32. The returned Field will safely and explicitly represent `nil` when appropriate.
func Uint32s ¶ added in v1.3.8
Uint32s constructs a field that carries a slice of unsigned integers.
func Uint64p ¶ added in v1.3.8
Uint64p constructs a field that carries a *uint64. The returned Field will safely and explicitly represent `nil` when appropriate.
func Uint64s ¶ added in v1.3.8
Uint64s constructs a field that carries a slice of unsigned integers.
func Uint8p ¶ added in v1.3.8
Uint8p constructs a field that carries a *uint8. The returned Field will safely and explicitly represent `nil` when appropriate.
func Uintp ¶ added in v1.3.8
Uintp constructs a field that carries a *uint. The returned Field will safely and explicitly represent `nil` when appropriate.
func Uintptrp ¶ added in v1.3.8
Uintptrp constructs a field that carries a *uintptr. The returned Field will safely and explicitly represent `nil` when appropriate.
type LevelEnablerFunc ¶ added in v1.3.8
LevelEnablerFunc is a convenient way to implement core.LevelEnabler with an anonymous function.
It's particularly useful when splitting log output between different outputs (e.g., standard error and standard out). For sample code, see the package-level AdvancedConfiguration example.
type Log ¶
type Log struct { Config *LogConfig // 配置对象 // 日志方法 Debug func(msg string, args ...interface{}) Info func(msg string, args ...interface{}) Warning func(msg string, args ...interface{}) Error func(msg string, args ...interface{}) Panic func(msg string, args ...interface{}) Fatal func(msg string, args ...interface{}) }
Log 日志核心对象
var (
Tmp *Log
)
func GetProductLog ¶ added in v1.3.6
GetProductLog 获取开发环境的日志
func NewWithConfig ¶ added in v1.0.3
NewWithConfig 创建zap实例
func NewWithDebug ¶ added in v1.3.4
NewWithDebug 根据debug值和日志路径创建日志对象
type LogConfig ¶
type LogConfig struct { Debug bool `env:"debug" yaml:"debug" json:"debug"` // 是否为debug模式 LogLevel string `env:"log_level" yaml:"log_level" json:"log_level"` // 日志级别 IsWriteDebug bool `env:"is_write_debug" yaml:"is_write_debug" json:"is_write_debug"` // 是否将debug日志写入文件 IsShowConsole bool `env:"is_show_console" yaml:"is_show_console" json:"is_show_console"` // 是否在控制台展示 OpenJsonLog bool `env:"open_json_log" yaml:"open_json_log" json:"open_json_log"` // 是否开启json日志格式 OpenFileName bool `env:"open_file_name" yaml:"open_file_name" json:"open_file_name"` // 是否输出文件名和行号 LogFilePath string `env:"log_file_path" yaml:"log_file_path" json:"log_file_path"` // 日志路径 MaxSize uint `env:"max_size" yaml:"max_size" json:"max_size"` // 日志最大保存多少M MaxBackups uint `env:"max_backups" yaml:"max_backups" json:"max_backups"` // 日志保留多少个备份 MaxAge uint `env:"max_age" yaml:"max_age" json:"max_age"` // 最多保留多少天日志 Compress bool `env:"compress" yaml:"compress" json:"compress"` // 是否压缩 }
Config zap日志配置核心对象
type Logger ¶ added in v1.0.0
type Logger struct {
// contains filtered or unexported fields
}
A Logger provides fast, leveled, structured logging. All methods are safe for concurrent use.
The Logger is designed for contexts in which every microsecond and every allocation matters, so its API intentionally favors performance and type safety over brevity. For most applications, the SugaredLogger strikes a better balance between performance and ergonomics.
func New ¶
New constructs a new Logger from the provided core.Core and Options. If the passed core.Core is nil, it falls back to using a no-op implementation.
This is the most flexible way to construct a Logger, but also the most verbose. For typical use cases, the highly-opinionated presets (NewProduction, NewDevelopment, and NewExample) or the Config struct are more convenient.
For sample code, see the package-level AdvancedConfiguration example.
func NewDevelopment ¶ added in v1.3.8
NewDevelopment builds a development Logger that writes DebugLevel and above logs to standard error in a human-friendly format.
It's a shortcut for NewDevelopmentConfig().Build(...Option).
func NewExample ¶ added in v1.3.8
NewExample builds a Logger that's designed for use in zap's testable examples. It writes DebugLevel and above logs to standard out as JSON, but omits the timestamp and calling function to keep example output short and deterministic.
func NewNop ¶ added in v1.3.8
func NewNop() *Logger
NewNop 返回一个无操作Logger。它从不写日志或内部错误,也从不运行用户定义的钩子。 使用WithOptions替换无操作Logger的Core或错误输出可以重新启用日志记录。
func NewProduction ¶ added in v1.3.8
NewProduction 构建一个合理的生产日志程序,将info级别及以上级别的日志作为JSON写入标准错误。 是NewProductionConfig().Build(...Option)的快捷方式
func (*Logger) Check ¶ added in v1.3.8
Check returns a CheckedEntry if logging a message at the specified level is enabled. It's a completely optional optimization; in high-performance applications, Check can help avoid allocating a slice to hold fields.
func (*Logger) DPanic ¶ added in v1.3.8
DPanic logs a message at DPanicLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.
If the logger is in development mode, it then panics (DPanic means "development panic"). This is useful for catching errors that are recoverable, but shouldn't ever happen.
func (*Logger) Debug ¶ added in v1.3.8
Debug logs a message at DebugLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.
func (*Logger) Error ¶ added in v1.0.0
Error logs a message at ErrorLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.
func (*Logger) Fatal ¶ added in v1.3.8
Fatal logs a message at FatalLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.
The logger then calls os.Exit(1), even if logging at FatalLevel is disabled.
func (*Logger) Info ¶ added in v1.0.0
Info logs a message at InfoLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.
func (*Logger) Named ¶ added in v1.3.8
Named adds a new path segment to the logger's name. Segments are joined by periods. By default, Loggers are unnamed.
func (*Logger) Panic ¶ added in v1.3.8
Panic logs a message at PanicLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.
The logger then panics, even if logging at PanicLevel is disabled.
func (*Logger) Sugar ¶ added in v1.3.8
func (log *Logger) Sugar() *SugaredLogger
Sugar wraps the Logger to provide a more ergonomic, but slightly slower, API. 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) Sync ¶ added in v1.3.8
Sync calls the underlying Core's Sync method, flushing any buffered log entries. Applications should take care to call Sync before exiting.
func (*Logger) Warn ¶ added in v1.3.8
Warn logs a message at WarnLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.
func (*Logger) With ¶ added in v1.3.8
With creates a child logger and adds structured context to it. Fields added to the child don't affect the parent, and vice versa.
func (*Logger) WithOptions ¶ added in v1.3.8
WithOptions clones the current Logger, applies the supplied Options, and returns the resulting Logger. It's safe to use concurrently.
type Option ¶ added in v1.3.8
type Option interface {
// contains filtered or unexported methods
}
Option 配置日志对象
func AddCaller ¶ added in v1.3.8
func AddCaller() Option
AddCaller configures the Logger to annotate each message with the filename, line number, and function name of zap's caller. See also WithCaller.
func AddCallerSkip ¶ added in v1.3.8
AddCallerSkip increases the number of callers skipped by caller annotation (as enabled by the AddCaller option). When building wrappers around the Logger and SugaredLogger, supplying this Option prevents zap from always reporting the wrapper code as the caller.
func AddStacktrace ¶ added in v1.3.8
func AddStacktrace(lvl core.LevelEnabler) Option
AddStacktrace configures the Logger to record a stack trace for all messages at or above a given level.
func Development ¶ added in v1.3.8
func Development() Option
Development puts the logger in development mode, which makes DPanic-level logs panic instead of simply logging an error.
func ErrorOutput ¶ added in v1.3.8
func ErrorOutput(w core.WriteSyncer) Option
ErrorOutput sets the destination for errors generated by the Logger. Note that this option only affects internal errors; for sample code that sends error-level logs to a different location from info- and debug-level logs, see the package-level AdvancedConfiguration example.
The supplied WriteSyncer must be safe for concurrent use. The Open and core.Lock functions are the simplest ways to protect files with a mutex.
func Hooks ¶ added in v1.3.8
Hooks registers functions which will be called each time the Logger writes out an Entry. Repeated use of Hooks is additive.
Hooks are useful for simple side effects, like capturing metrics for the number of emitted logs. More complex side effects, including anything that requires access to the Entry's structured fields, should be implemented as a core.Core instead. See core.RegisterHooks for details.
func IncreaseLevel ¶ added in v1.3.8
func IncreaseLevel(lvl core.LevelEnabler) Option
IncreaseLevel increase the level of the logger. It has no effect if the passed in level tries to decrease the level of the logger.
func OnFatal ¶ added in v1.3.8
func OnFatal(action core.CheckWriteAction) Option
OnFatal sets the action to take on fatal logs.
func WithCaller ¶ added in v1.3.8
WithCaller configures the Logger to annotate each message with the filename, line number, and function name of zap's caller, or not, depending on the value of enabled. This is a generalized form of AddCaller.
type SamplingConfig ¶ added in v1.3.8
type SamplingConfig struct { Initial int `json:"initial" yaml:"initial"` Thereafter int `json:"thereafter" yaml:"thereafter"` Hook func(core.Entry, core.SamplingDecision) `json:"-" yaml:"-"` }
SamplingConfig 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.
If specified, the Sampler will invoke the Hook after each decision.
Values configured here are per-second. See core.NewSamplerWithOptions for details.
type Sink ¶ added in v1.3.8
type Sink interface { core.WriteSyncer io.Closer }
Sink defines the interface to write to and close logger destinations.
type SugaredLogger ¶ added in v1.3.8
type SugaredLogger struct {
// contains filtered or unexported fields
}
SugaredLogger 包含了基础的Logger,但是API更轻量级。任何Logger都能够转换为SugaredLogger的方法。
func (*SugaredLogger) DPanic ¶ added in v1.3.8
func (s *SugaredLogger) DPanic(args ...interface{})
DPanic 使用 fmt.Sprint 结构化输出日志消息
func (*SugaredLogger) DPanicf ¶ added in v1.3.8
func (s *SugaredLogger) DPanicf(template string, args ...interface{})
DPanicf 使用 fmt.Sprintf 记录模板消息
func (*SugaredLogger) DPanicw ¶ added in v1.3.8
func (s *SugaredLogger) DPanicw(msg string, keysAndValues ...interface{})
DPanicw logs a message with some additional context. In development, the logger then panics. (See DPanicLevel for details.) The variadic key-value pairs are treated as they are in With.
func (*SugaredLogger) Debug ¶ added in v1.3.8
func (s *SugaredLogger) Debug(args ...interface{})
Debug 使用 fmt.Sprint 结构输出日志消息
func (*SugaredLogger) Debugf ¶ added in v1.3.8
func (s *SugaredLogger) Debugf(template string, args ...interface{})
Debugf 使用 fmt.Sprintf 记录模板消息
func (*SugaredLogger) Debugw ¶ added in v1.3.8
func (s *SugaredLogger) Debugw(msg string, keysAndValues ...interface{})
Debugw 使用 fmt.Sprintf 记录模板消息
func (*SugaredLogger) Desugar ¶ added in v1.3.8
func (s *SugaredLogger) Desugar() *Logger
Desugar 取消包裹SugaredLogger,暴露一个原始的Logger
func (*SugaredLogger) Error ¶ added in v1.3.8
func (s *SugaredLogger) Error(args ...interface{})
Error 使用 fmt.Sprint 结构化输出日志消息
func (*SugaredLogger) Errorf ¶ added in v1.3.8
func (s *SugaredLogger) Errorf(template string, args ...interface{})
Errorf 使用 fmt.Sprintf 记录模板消息
func (*SugaredLogger) Errorw ¶ added in v1.3.8
func (s *SugaredLogger) Errorw(msg string, keysAndValues ...interface{})
Errorw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.
func (*SugaredLogger) Fatal ¶ added in v1.3.8
func (s *SugaredLogger) Fatal(args ...interface{})
Fatal 使用 fmt.Sprint 结构化输出日志消息,然后调用 os.Exit.
func (*SugaredLogger) Fatalf ¶ added in v1.3.8
func (s *SugaredLogger) Fatalf(template string, args ...interface{})
Fatalf 使用 fmt.Sprintf 记录模板消息, 然后调用 os.Exit.
func (*SugaredLogger) Fatalw ¶ added in v1.3.8
func (s *SugaredLogger) Fatalw(msg string, keysAndValues ...interface{})
Fatalw logs a message with some additional context, then calls os.Exit. The variadic key-value pairs are treated as they are in With.
func (*SugaredLogger) Info ¶ added in v1.3.8
func (s *SugaredLogger) Info(args ...interface{})
Info 使用 fmt.Sprint 结构化输出日志消息
func (*SugaredLogger) Infof ¶ added in v1.3.8
func (s *SugaredLogger) Infof(template string, args ...interface{})
Infof 使用 fmt.Sprintf 记录模板消息
func (*SugaredLogger) Infow ¶ added in v1.3.8
func (s *SugaredLogger) Infow(msg string, keysAndValues ...interface{})
Infow logs a message with some additional context. The variadic key-value pairs are treated as they are in With.
func (*SugaredLogger) Named ¶ added in v1.3.8
func (s *SugaredLogger) Named(name string) *SugaredLogger
Named 修改Logger的名称
func (*SugaredLogger) Panic ¶ added in v1.3.8
func (s *SugaredLogger) Panic(args ...interface{})
Panic 使用 fmt.Sprint 结构化输出日志消息,然后调用panic
func (*SugaredLogger) Panicf ¶ added in v1.3.8
func (s *SugaredLogger) Panicf(template string, args ...interface{})
Panicf 使用 fmt.Sprintf 记录模板消息
func (*SugaredLogger) Panicw ¶ added in v1.3.8
func (s *SugaredLogger) Panicw(msg string, keysAndValues ...interface{})
Panicw logs a message with some additional context, then panics. The variadic key-value pairs are treated as they are in With.
func (*SugaredLogger) Sync ¶ added in v1.3.8
func (s *SugaredLogger) Sync() error
Sync flushes any buffered log entries.
func (*SugaredLogger) Warn ¶ added in v1.3.8
func (s *SugaredLogger) Warn(args ...interface{})
Warn 使用 fmt.Sprint 结构化输出日志消息
func (*SugaredLogger) Warnf ¶ added in v1.3.8
func (s *SugaredLogger) Warnf(template string, args ...interface{})
Warnf 使用 fmt.Sprintf 记录模板消息
func (*SugaredLogger) Warnw ¶ added in v1.3.8
func (s *SugaredLogger) Warnw(msg string, keysAndValues ...interface{})
Warnw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.
func (*SugaredLogger) With ¶ added in v1.3.8
func (s *SugaredLogger) With(args ...interface{}) *SugaredLogger
With 添加日志上下文