Movatterモバイル変換


[0]ホーム

URL:


zap

packagemodule
v1.27.1Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2025 License:MITImports:23Imported by:112,912

Details

Repository

github.com/uber-go/zap

Links

README

⚡ zap

Blazing fast, structured, leveled logging in Go.

Zap logo

GoDocBuild StatusCoverage Status

Installation

go get -u go.uber.org/zap

Note that zap only supports the two most recent minor versions of Go.

Quick Start

In contexts where performance is nice, but not critical, use theSugaredLogger. It's 4-10x faster than other structured loggingpackages and includes both structured andprintf-style APIs.

logger, _ := zap.NewProduction()defer logger.Sync() // flushes buffer, if anysugar := logger.Sugar()sugar.Infow("failed to fetch URL",  // Structured context as loosely typed key-value pairs.  "url", url,  "attempt", 3,  "backoff", time.Second,)sugar.Infof("Failed to fetch URL: %s", url)

When performance and type safety are critical, use theLogger. It's evenfaster than theSugaredLogger and allocates far less, but it only supportsstructured logging.

logger, _ := zap.NewProduction()defer logger.Sync()logger.Info("failed to fetch URL",  // Structured context as strongly typed Field values.  zap.String("url", url),  zap.Int("attempt", 3),  zap.Duration("backoff", time.Second),)

See thedocumentation andFAQ for more details.

Performance

For applications that log in the hot path, reflection-based serialization andstring formatting are prohibitively expensive — they're CPU-intensiveand make many small allocations. Put differently, usingencoding/json andfmt.Fprintf to log tons ofinterface{}s makes your application slow.

Zap takes a different approach. It includes a reflection-free, zero-allocationJSON encoder, and the baseLogger strives to avoid serialization overheadand allocations wherever possible. By building the high-levelSugaredLoggeron that foundation, zap lets userschoose when they need to count everyallocation and when they'd prefer a more familiar, loosely typed API.

As measured by its ownbenchmarking suite, not only is zap more performantthan comparable structured logging packages — it's also faster than thestandard library. Like all benchmarks, take these with a grain of salt.1

Log a message and 10 fields:

PackageTimeTime % to zapObjects Allocated
⚡ zap656 ns/op+0%5 allocs/op
⚡ zap (sugared)935 ns/op+43%10 allocs/op
zerolog380 ns/op-42%1 allocs/op
go-kit2249 ns/op+243%57 allocs/op
slog (LogAttrs)2479 ns/op+278%40 allocs/op
slog2481 ns/op+278%42 allocs/op
apex/log9591 ns/op+1362%63 allocs/op
log1511393 ns/op+1637%75 allocs/op
logrus11654 ns/op+1677%79 allocs/op

Log a message with a logger that already has 10 fields of context:

PackageTimeTime % to zapObjects Allocated
⚡ zap67 ns/op+0%0 allocs/op
⚡ zap (sugared)84 ns/op+25%1 allocs/op
zerolog35 ns/op-48%0 allocs/op
slog193 ns/op+188%0 allocs/op
slog (LogAttrs)200 ns/op+199%0 allocs/op
go-kit2460 ns/op+3572%56 allocs/op
log159038 ns/op+13390%70 allocs/op
apex/log9068 ns/op+13434%53 allocs/op
logrus10521 ns/op+15603%68 allocs/op

Log a static string, without any context orprintf-style templating:

PackageTimeTime % to zapObjects Allocated
⚡ zap63 ns/op+0%0 allocs/op
⚡ zap (sugared)81 ns/op+29%1 allocs/op
zerolog32 ns/op-49%0 allocs/op
standard library124 ns/op+97%1 allocs/op
slog196 ns/op+211%0 allocs/op
slog (LogAttrs)200 ns/op+217%0 allocs/op
go-kit213 ns/op+238%9 allocs/op
apex/log771 ns/op+1124%5 allocs/op
logrus1439 ns/op+2184%23 allocs/op
log152069 ns/op+3184%20 allocs/op

Development Status: Stable

All APIs are finalized, and no breaking changes will be made in the 1.x seriesof releases. Users of semver-aware dependency management systems should pinzap to^1.

Contributing

We encourage and support an active, healthy community of contributors —including you! Details are in thecontribution guide andthecode of conduct. The zap maintainers keep an eye onissues and pull requests, but you can also report any negative conduct tooss-conduct@uber.com. That email list is a private, safe space; even the zapmaintainers don't have access, so don't hesitate to hold us to a highstandard.


Released under theMIT License.

1 In particular, keep in mind that we may bebenchmarking against slightly older versions of other packages. Versions arepinned in thebenchmarks/go.mod file.

Documentation

Overview

Package zap provides fast, structured, leveled logging.

For applications that log in the hot path, reflection-based serializationand string formatting are prohibitively expensive - they're CPU-intensiveand make many small allocations. Put differently, using json.Marshal andfmt.Fprintf to log tons of interface{} makes your application slow.

Zap takes a different approach. It includes a reflection-free,zero-allocation JSON encoder, and the base Logger strives to avoidserialization overhead and allocations wherever possible. By building thehigh-level SugaredLogger on that foundation, zap lets users choose whenthey need to count every allocation and when they'd prefer a more familiar,loosely typed API.

Choosing a Logger

In contexts where performance is nice, but not critical, use theSugaredLogger. It's 4-10x faster than other structured logging packages andsupports both structured and printf-style logging. Like log15 and go-kit,the SugaredLogger's structured logging APIs are loosely typed and accept avariadic number of key-value pairs. (For more advanced use cases, they alsoaccept strongly typed fields - see the SugaredLogger.With documentation fordetails.)

sugar := zap.NewExample().Sugar()defer sugar.Sync()sugar.Infow("failed to fetch URL",  "url", "http://example.com",  "attempt", 3,  "backoff", time.Second,)sugar.Infof("failed to fetch URL: %s", "http://example.com")

By default, loggers are unbuffered. However, since zap's low-level APIsallow buffering, calling Sync before letting your process exit is a goodhabit.

In the rare contexts where every microsecond and every allocation matter,use the Logger. It's even faster than the SugaredLogger and allocates farless, but it only supports strongly-typed, structured logging.

logger := zap.NewExample()defer logger.Sync()logger.Info("failed to fetch URL",  zap.String("url", "http://example.com"),  zap.Int("attempt", 3),  zap.Duration("backoff", time.Second),)

Choosing between the Logger and SugaredLogger doesn't need to be anapplication-wide decision: converting between the two is simple andinexpensive.

logger := zap.NewExample()defer logger.Sync()sugar := logger.Sugar()plain := sugar.Desugar()

Configuring Zap

The simplest way to build a Logger is to use zap's opinionated presets:NewExample, NewProduction, and NewDevelopment. These presets build a loggerwith a single function call:

logger, err := zap.NewProduction()if err != nil {  log.Fatalf("can't initialize zap logger: %v", err)}defer logger.Sync()

Presets are fine for small projects, but larger projects and organizationsnaturally require a bit more customization. For most users, zap's Configstruct strikes the right balance between flexibility and convenience. Seethe package-level BasicConfiguration example for sample code.

More unusual configurations (splitting output between files, sending logsto a message queue, etc.) are possible, but require direct use ofgo.uber.org/zap/zapcore. See the package-level AdvancedConfigurationexample for sample code.

Extending Zap

The zap package itself is a relatively thin wrapper around the interfacesin go.uber.org/zap/zapcore. Extending zap to support a new encoding (e.g.,BSON), a new log sink (e.g., Kafka), or something more exotic (perhaps anexception aggregation service, like Sentry or Rollbar) typically requiresimplementing the zapcore.Encoder, zapcore.WriteSyncer, or zapcore.Coreinterfaces. See the zapcore documentation for details.

Similarly, package authors can use the high-performance Encoder and Coreimplementations in the zapcore package to build their own loggers.

Frequently Asked Questions

An FAQ covering everything from installation errors to design decisions isavailable athttps://github.com/uber-go/zap/blob/master/FAQ.md.

Example (AdvancedConfiguration)
package mainimport ("io""os""go.uber.org/zap""go.uber.org/zap/zapcore")func main() {// The bundled Config struct only supports the most common configuration// options. More complex needs, like splitting logs between multiple files// or writing to non-file outputs, require use of the zapcore package.//// In this example, imagine we're both sending our logs to Kafka and writing// them to the console. We'd like to encode the console output and the Kafka// topics differently, and we'd also like special treatment for// high-priority logs.// First, define our level-handling logic.highPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {return lvl >= zapcore.ErrorLevel})lowPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {return lvl < zapcore.ErrorLevel})// Assume that we have clients for two Kafka topics. The clients implement// zapcore.WriteSyncer and are safe for concurrent use. (If they only// implement io.Writer, we can use zapcore.AddSync to add a no-op Sync// method. If they're not safe for concurrent use, we can add a protecting// mutex with zapcore.Lock.)topicDebugging := zapcore.AddSync(io.Discard)topicErrors := zapcore.AddSync(io.Discard)// High-priority output should also go to standard error, and low-priority// output should also go to standard out.consoleDebugging := zapcore.Lock(os.Stdout)consoleErrors := zapcore.Lock(os.Stderr)// Optimize the Kafka output for machine consumption and the console output// for human operators.kafkaEncoder := zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig())consoleEncoder := zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig())// Join the outputs, encoders, and level-handling functions into// zapcore.Cores, then tee the four cores together.core := zapcore.NewTee(zapcore.NewCore(kafkaEncoder, topicErrors, highPriority),zapcore.NewCore(consoleEncoder, consoleErrors, highPriority),zapcore.NewCore(kafkaEncoder, topicDebugging, lowPriority),zapcore.NewCore(consoleEncoder, consoleDebugging, lowPriority),)// From a zapcore.Core, it's easy to construct a Logger.logger := zap.New(core)defer logger.Sync()logger.Info("constructed a logger")}

Example (BasicConfiguration)
package mainimport ("encoding/json""go.uber.org/zap")func main() {// For some users, the presets offered by the NewProduction, NewDevelopment,// and NewExample constructors won't be appropriate. For most of those// users, the bundled Config struct offers the right balance of flexibility// and convenience. (For more complex needs, see the AdvancedConfiguration// example.)//// See the documentation for Config and zapcore.EncoderConfig for all the// available options.rawJSON := []byte(`{  "level": "debug",  "encoding": "json",  "outputPaths": ["stdout", "/tmp/logs"],  "errorOutputPaths": ["stderr"],  "initialFields": {"foo": "bar"},  "encoderConfig": {    "messageKey": "message",    "levelKey": "level",    "levelEncoder": "lowercase"  }}`)var cfg zap.Configif err := json.Unmarshal(rawJSON, &cfg); err != nil {panic(err)}logger := zap.Must(cfg.Build())defer logger.Sync()logger.Info("logger construction succeeded")}
Output:{"level":"info","message":"logger construction succeeded","foo":"bar"}

Example (Presets)
package mainimport ("time""go.uber.org/zap")func main() {// Using zap's preset constructors is the simplest way to get a feel for the// package, but they don't allow much customization.logger := zap.NewExample() // or NewProduction, or NewDevelopmentdefer logger.Sync()const url = "http://example.com"// In most circumstances, use the SugaredLogger. It's 4-10x faster than most// other structured logging packages and has a familiar, loosely-typed API.sugar := logger.Sugar()sugar.Infow("Failed to fetch URL.",// Structured context as loosely typed key-value pairs."url", url,"attempt", 3,"backoff", time.Second,)sugar.Infof("Failed to fetch URL: %s", url)// In the unusual situations where every microsecond matters, use the// Logger. It's even faster than the SugaredLogger, but only supports// structured logging.logger.Info("Failed to fetch URL.",// Structured context as strongly typed fields.zap.String("url", url),zap.Int("attempt", 3),zap.Duration("backoff", time.Second),)}
Output:{"level":"info","msg":"Failed to fetch URL.","url":"http://example.com","attempt":3,"backoff":"1s"}{"level":"info","msg":"Failed to fetch URL: http://example.com"}{"level":"info","msg":"Failed to fetch URL.","url":"http://example.com","attempt":3,"backoff":"1s"}

Index

Examples

Constants

View Source
const (// 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)

Variables

This section is empty.

Functions

funcCombineWriteSyncers

func CombineWriteSyncers(writers ...zapcore.WriteSyncer)zapcore.WriteSyncer

CombineWriteSyncers is a utility that combines multiple WriteSyncers into asingle, locked WriteSyncer. If no inputs are supplied, it returns a no-opWriteSyncer.

It's provided purely as a convenience; the result is no different fromusing zapcore.NewMultiWriteSyncer and zapcore.Lock individually.

funcDictObjectadded inv1.27.1

func DictObject(val ...Field)zapcore.ObjectMarshaler

DictObject constructs azapcore.ObjectMarshaler with the given list of fields.The resulting object marshaler can be used as input toObject,Objects, orany other functions that expect an object marshaler.

Example
package mainimport ("time""go.uber.org/zap""go.uber.org/zap/zapcore")func main() {logger := zap.NewExample()defer logger.Sync()// Use DictObject to create zapcore.ObjectMarshaler implementations from Field arrays,// then use the Object and Objects field constructors to turn them back into a Field.logger.Debug("worker received job",zap.Object("w1",zap.DictObject(zap.Int("id", 402000),zap.String("description", "compress image data"),zap.Int("priority", 3),),))d1 := 68 * time.Millisecondd2 := 79 * time.Millisecondd3 := 57 * time.Millisecondlogger.Info("worker status checks",zap.Objects("job batch enqueued",[]zapcore.ObjectMarshaler{zap.DictObject(zap.String("worker", "w1"),zap.Int("load", 419),zap.Duration("latency", d1),),zap.DictObject(zap.String("worker", "w2"),zap.Int("load", 520),zap.Duration("latency", d2),),zap.DictObject(zap.String("worker", "w3"),zap.Int("load", 310),zap.Duration("latency", d3),),},))}
Output:{"level":"debug","msg":"worker received job","w1":{"id":402000,"description":"compress image data","priority":3}}{"level":"info","msg":"worker status checks","job batch enqueued":[{"worker":"w1","load":419,"latency":"68ms"},{"worker":"w2","load":520,"latency":"79ms"},{"worker":"w3","load":310,"latency":"57ms"}]}

funcLevelFlag

func LevelFlag(namestring, defaultLevelzapcore.Level, usagestring) *zapcore.Level

LevelFlag uses the standard library's flag.Var to declare a global flagwith the specified name, default, and usage guidance. The returned value isa pointer to the value of the flag.

If you don't want to use the flag package's global state, you can use anynon-nil *Level as a flag.Value with your own *flag.FlagSet.

funcNewDevelopmentEncoderConfig

func NewDevelopmentEncoderConfig()zapcore.EncoderConfig

NewDevelopmentEncoderConfig returns an opinionated EncoderConfig fordevelopment environments.

Messages encoded with this configuration will use Zap's console encoderintended to print human-readable output.It will print log messages with the following information:

  • The log level (e.g. "INFO", "ERROR").
  • The time in ISO8601 format (e.g. "2017-01-01T12:00:00Z").
  • The message passed to the log statement.
  • If available, a short path to the file and line numberwhere the log statement was issued.The logger configuration determines whether this field is captured.
  • If available, a stacktrace from the linewhere the log statement was issued.The logger configuration determines whether this field is captured.

By default, the following formats are used for different types:

  • Time is formatted in ISO8601 format (e.g. "2017-01-01T12:00:00Z").
  • Duration is formatted as a string (e.g. "1.234s").

You may change these by setting the appropriate fields in the returnedobject.For example, use the following to change the time encoding format:

cfg := zap.NewDevelopmentEncoderConfig()cfg.EncodeTime = zapcore.ISO8601TimeEncoder

funcNewProductionEncoderConfig

func NewProductionEncoderConfig()zapcore.EncoderConfig

NewProductionEncoderConfig returns an opinionated EncoderConfig forproduction environments.

Messages encoded with this configuration will be JSON-formattedand will have the following keys by default:

  • "level": The logging level (e.g. "info", "error").
  • "ts": The current time in number of seconds since the Unix epoch.
  • "msg": The message passed to the log statement.
  • "caller": If available, a short path to the file and line numberwhere the log statement was issued.The logger configuration determines whether this field is captured.
  • "stacktrace": If available, a stack trace from the linewhere the log statement was issued.The logger configuration determines whether this field is captured.

By default, the following formats are used for different types:

  • Time is formatted as floating-point number of seconds since the Unixepoch.
  • Duration is formatted as floating-point number of seconds.

You may change these by setting the appropriate fields in the returnedobject.For example, use the following to change the time encoding format:

cfg := zap.NewProductionEncoderConfig()cfg.EncodeTime = zapcore.ISO8601TimeEncoder

funcNewStdLog

func NewStdLog(l *Logger) *log.Logger

NewStdLog returns a *log.Logger which writes to the supplied zap Logger atInfoLevel. To redirect the standard library's package-global loggingfunctions, use RedirectStdLog instead.

Example
package mainimport ("go.uber.org/zap")func main() {logger := zap.NewExample()defer logger.Sync()std := zap.NewStdLog(logger)std.Print("standard logger wrapper")}
Output:{"level":"info","msg":"standard logger wrapper"}

funcNewStdLogAtadded inv1.7.0

func NewStdLogAt(l *Logger, levelzapcore.Level) (*log.Logger,error)

NewStdLogAt returns *log.Logger which writes to supplied zap logger atrequired level.

funcOpen

func Open(paths ...string) (zapcore.WriteSyncer, func(),error)

Open is a high-level wrapper that takes a variadic number of URLs, opens orcreates each of the specified resources, and combines them into a lockedWriteSyncer. It also returns any error encountered and a function to closeany opened files.

Passing no URLs returns a no-op WriteSyncer. Zap handles URLs without ascheme and URLs with the "file" scheme. Third-party code may registerfactories for other schemes using RegisterSink.

URLs with the "file" scheme must use absolute paths on the localfilesystem. No user, password, port, fragments, or query parameters areallowed, and the hostname must be empty or "localhost".

Since it's common to write logs to the local filesystem, URLs without ascheme (e.g., "/var/log/foo.log") are treated as local file paths. Withouta scheme, the special paths "stdout" and "stderr" are interpreted asos.Stdout and os.Stderr. When specified without a scheme, relative filepaths also work.

funcRedirectStdLog

func RedirectStdLog(l *Logger) func()

RedirectStdLog redirects output from the standard library's package-globallogger to the supplied logger at InfoLevel. Since zap already handles callerannotations, timestamps, etc., it automatically disables the standardlibrary's annotations and prefixing.

It returns a function to restore the original prefix and flags and reset thestandard library's output to os.Stderr.

Example
package mainimport ("log""go.uber.org/zap")func main() {logger := zap.NewExample()defer logger.Sync()undo := zap.RedirectStdLog(logger)defer undo()log.Print("redirected standard library")}
Output:{"level":"info","msg":"redirected standard library"}

funcRedirectStdLogAtadded inv1.8.0

func RedirectStdLogAt(l *Logger, levelzapcore.Level) (func(),error)

RedirectStdLogAt redirects output from the standard library's package-globallogger to the supplied logger at the specified level. Since zap alreadyhandles caller annotations, timestamps, etc., it automatically disables thestandard library's annotations and prefixing.

It returns a function to restore the original prefix and flags and reset thestandard library's output to os.Stderr.

funcRegisterEncoder

func RegisterEncoder(namestring, constructor func(zapcore.EncoderConfig) (zapcore.Encoder,error))error

RegisterEncoder registers an encoder constructor, which the Config structcan then reference. By default, the "json" and "console" encoders areregistered.

Attempting to register an encoder whose name is already taken returns anerror.

funcRegisterSinkadded inv1.9.0

func RegisterSink(schemestring, factory func(*url.URL) (Sink,error))error

RegisterSink registers a user-supplied factory for all sinks with aparticular scheme.

All schemes must be ASCII, valid under section 0.1 ofRFC 3986(https://tools.ietf.org/html/rfc3983#section-3.1), and must not alreadyhave a factory registered. Zap automatically registers a factory for the"file" scheme.

funcReplaceGlobals

func ReplaceGlobals(logger *Logger) func()

ReplaceGlobals replaces the global Logger and SugaredLogger, and returns afunction to restore the original values. It's safe for concurrent use.

Example
package mainimport ("go.uber.org/zap")func main() {logger := zap.NewExample()defer logger.Sync()undo := zap.ReplaceGlobals(logger)defer undo()zap.L().Info("replaced zap's global loggers")}
Output:{"level":"info","msg":"replaced zap's global loggers"}

Types

typeAtomicLevel

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

An AtomicLevel is an atomically changeable, dynamic logging level. It letsyou safely change the log level of a tree of loggers (the root logger andany children created by adding context) at runtime.

The AtomicLevel itself is an http.Handler that serves a JSON endpoint toalter its level.

AtomicLevels must be created with the NewAtomicLevel constructor to allocatetheir internal atomic pointer.

Example
package mainimport ("os""go.uber.org/zap""go.uber.org/zap/zapcore")func main() {atom := zap.NewAtomicLevel()// To keep the example deterministic, disable timestamps in the output.encoderCfg := zap.NewProductionEncoderConfig()encoderCfg.TimeKey = ""logger := zap.New(zapcore.NewCore(zapcore.NewJSONEncoder(encoderCfg),zapcore.Lock(os.Stdout),atom,))defer logger.Sync()logger.Info("info logging enabled")atom.SetLevel(zap.ErrorLevel)logger.Info("info logging disabled")}
Output:{"level":"info","msg":"info logging enabled"}

Example (Config)
package mainimport ("encoding/json""go.uber.org/zap")func main() {// The zap.Config struct includes an AtomicLevel. To use it, keep a// reference to the Config.rawJSON := []byte(`{"level": "info","outputPaths": ["stdout"],"errorOutputPaths": ["stderr"],"encoding": "json","encoderConfig": {"messageKey": "message","levelKey": "level","levelEncoder": "lowercase"}}`)var cfg zap.Configif err := json.Unmarshal(rawJSON, &cfg); err != nil {panic(err)}logger := zap.Must(cfg.Build())defer logger.Sync()logger.Info("info logging enabled")cfg.Level.SetLevel(zap.ErrorLevel)logger.Info("info logging disabled")}
Output:{"level":"info","message":"info logging enabled"}

funcNewAtomicLevel

func NewAtomicLevel()AtomicLevel

NewAtomicLevel creates an AtomicLevel with InfoLevel and above loggingenabled.

funcNewAtomicLevelAtadded inv1.3.0

func NewAtomicLevelAt(lzapcore.Level)AtomicLevel

NewAtomicLevelAt is a convenience function that creates an AtomicLeveland then calls SetLevel with the given level.

funcParseAtomicLeveladded inv1.21.0

func ParseAtomicLevel(textstring) (AtomicLevel,error)

ParseAtomicLevel parses an AtomicLevel based on a lowercase or all-caps ASCIIrepresentation of the log level. If the provided ASCII representation isinvalid an error is returned.

This is particularly useful when dealing with text input to configure loglevels.

func (AtomicLevel)Enabled

func (lvlAtomicLevel) Enabled(lzapcore.Level)bool

Enabled implements the zapcore.LevelEnabler interface, which allows theAtomicLevel to be used in place of traditional static levels.

func (AtomicLevel)Level

func (lvlAtomicLevel) Level()zapcore.Level

Level returns the minimum enabled log level.

func (AtomicLevel)MarshalTextadded inv1.3.0

func (lvlAtomicLevel) MarshalText() (text []byte, errerror)

MarshalText marshals the AtomicLevel to a byte slice. It uses the sametext representation as the static zapcore.Levels ("debug", "info", "warn","error", "dpanic", "panic", and "fatal").

func (AtomicLevel)ServeHTTP

func (lvlAtomicLevel) ServeHTTP(whttp.ResponseWriter, r *http.Request)

ServeHTTP is a simple JSON endpoint that can report on or change the currentlogging 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 thelogging 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 ora query parameter. The log level is URL encoded like:

level=debug

The request body takes precedence over the query parameter, if both arespecified.

This content type is the default for a curl PUT request. Following are twoexample curl requests that both set the logging level to debug.

curl -X PUT localhost:8080/log/level?level=debugcurl -X PUT localhost:8080/log/level -d level=debug

For any other content type, the payload is expected to be JSON encoded andlook 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

func (lvlAtomicLevel) SetLevel(lzapcore.Level)

SetLevel alters the logging level.

func (AtomicLevel)Stringadded inv1.4.0

func (lvlAtomicLevel) String()string

String returns the string representation of the underlying Level.

func (*AtomicLevel)UnmarshalText

func (lvl *AtomicLevel) UnmarshalText(text []byte)error

UnmarshalText unmarshals the text to an AtomicLevel. It uses the same textrepresentations as the static zapcore.Levels ("debug", "info", "warn","error", "dpanic", "panic", and "fatal").

typeConfig

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.LevelAtomicLevel `json:"level" yaml:"level"`// Development puts the logger in development mode, which changes the// behavior of DPanicLevel and takes stacktraces more liberally.Developmentbool `json:"development" yaml:"development"`// DisableCaller stops annotating logs with the calling function's file// name and line number. By default, all logs are annotated.DisableCallerbool `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.DisableStacktracebool `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.Encodingstring `json:"encoding" yaml:"encoding"`// EncoderConfig sets options for the chosen encoder. See// zapcore.EncoderConfig for details.EncoderConfigzapcore.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 doanything that can't be done with New, Options, and the variouszapcore.WriteSyncer and zapcore.Core wrappers, but it's a simpler way totoggle common options.

Note that Config intentionally supports only the most common options. Moreunusual logging setups (logging to network connections or message queues,splitting output between multiple files, etc.) are possible, but requiredirect use of the zapcore package. For sample code, see the package-levelBasicConfiguration and AdvancedConfiguration examples.

For an example showing runtime log level changes, see the documentation forAtomicLevel.

funcNewDevelopmentConfig

func NewDevelopmentConfig()Config

NewDevelopmentConfig builds a reasonable default development loggingconfiguration.Logging is enabled at DebugLevel and above, and uses a console encoder.Logs are written to standard error.Stacktraces are included on logs of WarnLevel and above.DPanicLevel logs will panic.

SeeNewDevelopmentEncoderConfig for informationon the default encoder configuration.

funcNewProductionConfig

func NewProductionConfig()Config

NewProductionConfig builds a reasonable default production loggingconfiguration.Logging is enabled at InfoLevel and above, and uses a JSON encoder.Logs are written to standard error.Stacktraces are included on logs of ErrorLevel and above.DPanicLevel logs will not panic, but will write a stacktrace.

Sampling is enabled at 100:100 by default,meaning that after the first 100 log entrieswith the same level and message in the same second,it will log every 100th entrywith the same level and message in the same second.You may disable this behavior by setting Sampling to nil.

SeeNewProductionEncoderConfig for informationon the default encoder configuration.

func (Config)Build

func (cfgConfig) Build(opts ...Option) (*Logger,error)

Build constructs a logger from the Config and Options.

typeFieldadded inv1.8.0

type Field =zapcore.Field

Field is an alias for Field. Aliasing this type dramaticallyimproves the navigability of this package's API documentation.

funcAny

func Any(keystring, value interface{})Field

Any takes a key and an arbitrary value and chooses the best way to representthem as a field, falling back to a reflection-based approach only ifnecessary.

Since byte/uint8 and rune/int32 are aliases, Any can't differentiate betweenthem. To minimize surprises, []byte values are treated as binary blobs, bytevalues are treated as uint8, and runes are always treated as integers.

funcArray

Array constructs a field with the given key and ArrayMarshaler. It providesa flexible, but still type-safe and efficient, way to add array-like typesto the logging context. The struct's MarshalLogArray method is called lazily.

funcBinary

func Binary(keystring, val []byte)Field

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.

funcBool

func Bool(keystring, valbool)Field

Bool constructs a field that carries a bool.

funcBoolpadded inv1.13.0

func Boolp(keystring, val *bool)Field

Boolp constructs a field that carries a *bool. The returned Field will safelyand explicitly represent `nil` when appropriate.

funcBools

func Bools(keystring, bs []bool)Field

Bools constructs a field that carries a slice of bools.

funcByteString

func ByteString(keystring, val []byte)Field

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), useBinary.

funcByteStrings

func ByteStrings(keystring, bss [][]byte)Field

ByteStrings constructs a field that carries a slice of []byte, each of whichmust be UTF-8 encoded text.

funcComplex128

func Complex128(keystring, valcomplex128)Field

Complex128 constructs a field that carries a complex number. Unlike mostnumeric fields, this costs an allocation (to convert the complex128 tointerface{}).

funcComplex128padded inv1.13.0

func Complex128p(keystring, val *complex128)Field

Complex128p constructs a field that carries a *complex128. The returned Field will safelyand explicitly represent `nil` when appropriate.

funcComplex128s

func Complex128s(keystring, nums []complex128)Field

Complex128s constructs a field that carries a slice of complex numbers.

funcComplex64

func Complex64(keystring, valcomplex64)Field

Complex64 constructs a field that carries a complex number. Unlike mostnumeric fields, this costs an allocation (to convert the complex64 tointerface{}).

funcComplex64padded inv1.13.0

func Complex64p(keystring, val *complex64)Field

Complex64p constructs a field that carries a *complex64. The returned Field will safelyand explicitly represent `nil` when appropriate.

funcComplex64s

func Complex64s(keystring, nums []complex64)Field

Complex64s constructs a field that carries a slice of complex numbers.

funcDictadded inv1.26.0

func Dict(keystring, val ...Field)Field

Dict constructs a field containing the provided key-value pairs.It acts similar toObject, but with the fields specified as arguments.

Example
package mainimport ("go.uber.org/zap")func main() {logger := zap.NewExample()defer logger.Sync()logger.Info("login event",zap.Dict("event",zap.Int("id", 123),zap.String("name", "jane"),zap.String("status", "pending")))}
Output:{"level":"info","msg":"login event","event":{"id":123,"name":"jane","status":"pending"}}

funcDuration

func Duration(keystring, valtime.Duration)Field

Duration constructs a field with the given key and value. The encodercontrols how the duration is serialized.

funcDurationpadded inv1.13.0

func Durationp(keystring, val *time.Duration)Field

Durationp constructs a field that carries a *time.Duration. The returned Field will safelyand explicitly represent `nil` when appropriate.

funcDurations

func Durations(keystring, ds []time.Duration)Field

Durations constructs a field that carries a slice of time.Durations.

funcError

func Error(errerror)Field

Error is shorthand for the common idiom NamedError("error", err).

funcErrors

func Errors(keystring, errs []error)Field

Errors constructs a field that carries a slice of errors.

funcFloat32

func Float32(keystring, valfloat32)Field

Float32 constructs a field that carries a float32. The way thefloating-point value is represented is encoder-dependent, so marshaling isnecessarily lazy.

funcFloat32padded inv1.13.0

func Float32p(keystring, val *float32)Field

Float32p constructs a field that carries a *float32. The returned Field will safelyand explicitly represent `nil` when appropriate.

funcFloat32s

func Float32s(keystring, nums []float32)Field

Float32s constructs a field that carries a slice of floats.

funcFloat64

func Float64(keystring, valfloat64)Field

Float64 constructs a field that carries a float64. The way thefloating-point value is represented is encoder-dependent, so marshaling isnecessarily lazy.

funcFloat64padded inv1.13.0

func Float64p(keystring, val *float64)Field

Float64p constructs a field that carries a *float64. The returned Field will safelyand explicitly represent `nil` when appropriate.

funcFloat64s

func Float64s(keystring, nums []float64)Field

Float64s constructs a field that carries a slice of floats.

funcInlineadded inv1.17.0

Inline constructs a Field that is similar to Object, but itwill add the elements of the provided ObjectMarshaler to thecurrent namespace.

funcInt

func Int(keystring, valint)Field

Int constructs a field with the given key and value.

funcInt16

func Int16(keystring, valint16)Field

Int16 constructs a field with the given key and value.

funcInt16padded inv1.13.0

func Int16p(keystring, val *int16)Field

Int16p constructs a field that carries a *int16. The returned Field will safelyand explicitly represent `nil` when appropriate.

funcInt16s

func Int16s(keystring, nums []int16)Field

Int16s constructs a field that carries a slice of integers.

funcInt32

func Int32(keystring, valint32)Field

Int32 constructs a field with the given key and value.

funcInt32padded inv1.13.0

func Int32p(keystring, val *int32)Field

Int32p constructs a field that carries a *int32. The returned Field will safelyand explicitly represent `nil` when appropriate.

funcInt32s

func Int32s(keystring, nums []int32)Field

Int32s constructs a field that carries a slice of integers.

funcInt64

func Int64(keystring, valint64)Field

Int64 constructs a field with the given key and value.

funcInt64padded inv1.13.0

func Int64p(keystring, val *int64)Field

Int64p constructs a field that carries a *int64. The returned Field will safelyand explicitly represent `nil` when appropriate.

funcInt64s

func Int64s(keystring, nums []int64)Field

Int64s constructs a field that carries a slice of integers.

funcInt8

func Int8(keystring, valint8)Field

Int8 constructs a field with the given key and value.

funcInt8padded inv1.13.0

func Int8p(keystring, val *int8)Field

Int8p constructs a field that carries a *int8. The returned Field will safelyand explicitly represent `nil` when appropriate.

funcInt8s

func Int8s(keystring, nums []int8)Field

Int8s constructs a field that carries a slice of integers.

funcIntpadded inv1.13.0

func Intp(keystring, val *int)Field

Intp constructs a field that carries a *int. The returned Field will safelyand explicitly represent `nil` when appropriate.

funcInts

func Ints(keystring, nums []int)Field

Ints constructs a field that carries a slice of integers.

funcNamedError

func NamedError(keystring, errerror)Field

NamedError constructs a field that lazily stores err.Error() under theprovided key. Errors which also implement fmt.Formatter (like those producedby github.com/pkg/errors) will also have their verbose representation storedunder 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 functionis shorter and less repetitive.

funcNamespace

func Namespace(keystring)Field

Namespace creates a named, isolated scope within the logger's context. Allsubsequent fields will be added to the new namespace.

This helps prevent key collisions when injecting loggers into sub-componentsor third-party libraries.

Example
package mainimport ("go.uber.org/zap")func main() {logger := zap.NewExample()defer logger.Sync()logger.With(zap.Namespace("metrics"),zap.Int("counter", 1),).Info("tracked some metrics")}
Output:{"level":"info","msg":"tracked some metrics","metrics":{"counter":1}}

funcObject

func Object(keystring, valzapcore.ObjectMarshaler)Field

Object constructs a field with the given key and ObjectMarshaler. Itprovides a flexible, but still type-safe and efficient, way to add map- orstruct-like user-defined types to the logging context. The struct'sMarshalLogObject method is called lazily.

Example
package mainimport ("go.uber.org/zap""go.uber.org/zap/zapcore")type addr struct {IP   stringPort int}type request struct {URL    stringListen addrRemote addr}func (a addr) MarshalLogObject(enc zapcore.ObjectEncoder) error {enc.AddString("ip", a.IP)enc.AddInt("port", a.Port)return nil}func (r *request) MarshalLogObject(enc zapcore.ObjectEncoder) error {enc.AddString("url", r.URL)zap.Inline(r.Listen).AddTo(enc)return enc.AddObject("remote", r.Remote)}func main() {logger := zap.NewExample()defer logger.Sync()req := &request{URL:    "/test",Listen: addr{"127.0.0.1", 8080},Remote: addr{"127.0.0.1", 31200},}logger.Info("new request, in nested object", zap.Object("req", req))logger.Info("new request, inline", zap.Inline(req))}
Output:{"level":"info","msg":"new request, in nested object","req":{"url":"/test","ip":"127.0.0.1","port":8080,"remote":{"ip":"127.0.0.1","port":31200}}}{"level":"info","msg":"new request, inline","url":"/test","ip":"127.0.0.1","port":8080,"remote":{"ip":"127.0.0.1","port":31200}}

funcObjectValuesadded inv1.22.0

func ObjectValues[Tany, PObjectMarshalerPtr[T]](keystring, values []T)Field

ObjectValues constructs a field with the given key, holding a list of theprovided objects, where pointers to these objects can be marshaled by Zap.

Note that pointers to these objects must implement zapcore.ObjectMarshaler.That is, if you're trying to marshal a []Request, the MarshalLogObjectmethod must be declared on the *Request type, not the value (Request).If it's on the value, use Objects.

Given an object that implements MarshalLogObject on the pointer receiver,you can log a slice of those objects with ObjectValues like so:

type Request struct{ ... }func (r *Request) MarshalLogObject(enc zapcore.ObjectEncoder) errorvar requests []Request = ...logger.Info("sending requests", zap.ObjectValues("requests", requests))

If instead, you have a slice of pointers of such an object, use the Objectsfield constructor.

var requests []*Request = ...logger.Info("sending requests", zap.Objects("requests", requests))
Example
package mainimport ("go.uber.org/zap""go.uber.org/zap/zapcore")type addr struct {IP   stringPort int}type request struct {URL    stringListen addrRemote addr}func (a addr) MarshalLogObject(enc zapcore.ObjectEncoder) error {enc.AddString("ip", a.IP)enc.AddInt("port", a.Port)return nil}func (r *request) MarshalLogObject(enc zapcore.ObjectEncoder) error {enc.AddString("url", r.URL)zap.Inline(r.Listen).AddTo(enc)return enc.AddObject("remote", r.Remote)}func main() {logger := zap.NewExample()defer logger.Sync()// Use the ObjectValues field constructor when you have a list of// objects that do not implement zapcore.ObjectMarshaler directly,// but on their pointer receivers.logger.Debug("starting tunnels",zap.ObjectValues("addrs", []request{{URL:    "/foo",Listen: addr{"127.0.0.1", 8080},Remote: addr{"123.45.67.89", 4040},},{URL:    "/bar",Listen: addr{"127.0.0.1", 8080},Remote: addr{"127.0.0.1", 31200},},}))}
Output:{"level":"debug","msg":"starting tunnels","addrs":[{"url":"/foo","ip":"127.0.0.1","port":8080,"remote":{"ip":"123.45.67.89","port":4040}},{"url":"/bar","ip":"127.0.0.1","port":8080,"remote":{"ip":"127.0.0.1","port":31200}}]}

funcObjectsadded inv1.22.0

func Objects[Tzapcore.ObjectMarshaler](keystring, values []T)Field

Objects constructs a field with the given key, holding a list of theprovided objects that can be marshaled by Zap.

Note that these objects must implement zapcore.ObjectMarshaler directly.That is, if you're trying to marshal a []Request, the MarshalLogObjectmethod must be declared on the Request type, not its pointer (*Request).If it's on the pointer, use ObjectValues.

Given an object that implements MarshalLogObject on the value receiver, youcan log a slice of those objects with Objects like so:

type Author struct{ ... }func (a Author) MarshalLogObject(enc zapcore.ObjectEncoder) errorvar authors []Author = ...logger.Info("loading article", zap.Objects("authors", authors))

Similarly, given a type that implements MarshalLogObject on its pointerreceiver, you can log a slice of pointers to that object with Objects likeso:

type Request struct{ ... }func (r *Request) MarshalLogObject(enc zapcore.ObjectEncoder) errorvar requests []*Request = ...logger.Info("sending requests", zap.Objects("requests", requests))

If instead, you have a slice of values of such an object, use theObjectValues constructor.

var requests []Request = ...logger.Info("sending requests", zap.ObjectValues("requests", requests))
Example
package mainimport ("go.uber.org/zap""go.uber.org/zap/zapcore")type addr struct {IP   stringPort int}func (a addr) MarshalLogObject(enc zapcore.ObjectEncoder) error {enc.AddString("ip", a.IP)enc.AddInt("port", a.Port)return nil}func main() {logger := zap.NewExample()defer logger.Sync()// Use the Objects field constructor when you have a list of objects,// all of which implement zapcore.ObjectMarshaler.logger.Debug("opening connections",zap.Objects("addrs", []addr{{IP: "123.45.67.89", Port: 4040},{IP: "127.0.0.1", Port: 4041},{IP: "192.168.0.1", Port: 4042},}))}
Output:{"level":"debug","msg":"opening connections","addrs":[{"ip":"123.45.67.89","port":4040},{"ip":"127.0.0.1","port":4041},{"ip":"192.168.0.1","port":4042}]}

funcReflect

func Reflect(keystring, val interface{})Field

Reflect constructs a field with the given key and an arbitrary object. It usesan encoding-appropriate, reflection-based function to lazily serialize nearlyany object into the logging context, but it's relatively slow andallocation-heavy. Outside tests, Any is always a better choice.

If encoding fails (e.g., trying to serialize a map[int]string to JSON), Reflectincludes the error message in the final log output.

funcSkip

func Skip()Field

Skip constructs a no-op field, which is often useful when handling invalidinputs in other Field constructors.

funcStack

func Stack(keystring)Field

Stack constructs a field that stores a stacktrace of the current goroutineunder provided key. Keep in mind that taking a stacktrace is eager andexpensive (relatively speaking); this function both makes an allocation andtakes about two microseconds.

funcStackSkipadded inv1.16.0

func StackSkip(keystring, skipint)Field

StackSkip constructs a field similarly to Stack, but also skips the givennumber of frames from the top of the stacktrace.

funcString

func String(keystring, valstring)Field

String constructs a field with the given key and value.

funcStringer

func Stringer(keystring, valfmt.Stringer)Field

Stringer constructs a field with the given key and the output of the value'sString method. The Stringer's String method is called lazily.

funcStringersadded inv1.23.0

func Stringers[Tfmt.Stringer](keystring, values []T)Field

Stringers constructs a field with the given key, holding a list of theoutput provided by the value's String method

Given an object that implements String on the value receiver, youcan log a slice of those objects with Objects like so:

type Request struct{ ... }func (a Request) String() stringvar requests []Request = ...logger.Info("sending requests", zap.Stringers("requests", requests))

Note that these objects must implement fmt.Stringer directly.That is, if you're trying to marshal a []Request, the String methodmust be declared on the Request type, not its pointer (*Request).

funcStringpadded inv1.13.0

func Stringp(keystring, val *string)Field

Stringp constructs a field that carries a *string. The returned Field will safelyand explicitly represent `nil` when appropriate.

funcStrings

func Strings(keystring, ss []string)Field

Strings constructs a field that carries a slice of strings.

funcTime

func Time(keystring, valtime.Time)Field

Time constructs a Field with the given key and value. The encodercontrols how the time is serialized.

funcTimepadded inv1.13.0

func Timep(keystring, val *time.Time)Field

Timep constructs a field that carries a *time.Time. The returned Field will safelyand explicitly represent `nil` when appropriate.

funcTimes

func Times(keystring, ts []time.Time)Field

Times constructs a field that carries a slice of time.Times.

funcUint

func Uint(keystring, valuint)Field

Uint constructs a field with the given key and value.

funcUint16

func Uint16(keystring, valuint16)Field

Uint16 constructs a field with the given key and value.

funcUint16padded inv1.13.0

func Uint16p(keystring, val *uint16)Field

Uint16p constructs a field that carries a *uint16. The returned Field will safelyand explicitly represent `nil` when appropriate.

funcUint16s

func Uint16s(keystring, nums []uint16)Field

Uint16s constructs a field that carries a slice of unsigned integers.

funcUint32

func Uint32(keystring, valuint32)Field

Uint32 constructs a field with the given key and value.

funcUint32padded inv1.13.0

func Uint32p(keystring, val *uint32)Field

Uint32p constructs a field that carries a *uint32. The returned Field will safelyand explicitly represent `nil` when appropriate.

funcUint32s

func Uint32s(keystring, nums []uint32)Field

Uint32s constructs a field that carries a slice of unsigned integers.

funcUint64

func Uint64(keystring, valuint64)Field

Uint64 constructs a field with the given key and value.

funcUint64padded inv1.13.0

func Uint64p(keystring, val *uint64)Field

Uint64p constructs a field that carries a *uint64. The returned Field will safelyand explicitly represent `nil` when appropriate.

funcUint64s

func Uint64s(keystring, nums []uint64)Field

Uint64s constructs a field that carries a slice of unsigned integers.

funcUint8

func Uint8(keystring, valuint8)Field

Uint8 constructs a field with the given key and value.

funcUint8padded inv1.13.0

func Uint8p(keystring, val *uint8)Field

Uint8p constructs a field that carries a *uint8. The returned Field will safelyand explicitly represent `nil` when appropriate.

funcUint8s

func Uint8s(keystring, nums []uint8)Field

Uint8s constructs a field that carries a slice of unsigned integers.

funcUintpadded inv1.13.0

func Uintp(keystring, val *uint)Field

Uintp constructs a field that carries a *uint. The returned Field will safelyand explicitly represent `nil` when appropriate.

funcUintptr

func Uintptr(keystring, valuintptr)Field

Uintptr constructs a field with the given key and value.

funcUintptrpadded inv1.13.0

func Uintptrp(keystring, val *uintptr)Field

Uintptrp constructs a field that carries a *uintptr. The returned Field will safelyand explicitly represent `nil` when appropriate.

funcUintptrs

func Uintptrs(keystring, us []uintptr)Field

Uintptrs constructs a field that carries a slice of pointer addresses.

funcUints

func Uints(keystring, nums []uint)Field

Uints constructs a field that carries a slice of unsigned integers.

typeLevelEnablerFunc

type LevelEnablerFunc func(zapcore.Level)bool

LevelEnablerFunc is a convenient way to implement zapcore.LevelEnabler withan anonymous function.

It's particularly useful when splitting log output between differentoutputs (e.g., standard error and standard out). For sample code, see thepackage-level AdvancedConfiguration example.

func (LevelEnablerFunc)Enabled

func (fLevelEnablerFunc) Enabled(lvlzapcore.Level)bool

Enabled calls the wrapped function.

typeLogger

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

A Logger provides fast, leveled, structured logging. All methods are safefor concurrent use.

The Logger is designed for contexts in which every microsecond and everyallocation matters, so its API intentionally favors performance and typesafety over brevity. For most applications, the SugaredLogger strikes abetter balance between performance and ergonomics.

funcL

func L() *Logger

L returns the global Logger, which can be reconfigured with ReplaceGlobals.It's safe for concurrent use.

funcMustadded inv1.22.0

func Must(logger *Logger, errerror) *Logger

Must is a helper that wraps a call to a function returning (*Logger, error)and panics if the error is non-nil. It is intended for use in variableinitialization such as:

var logger = zap.Must(zap.NewProduction())

funcNew

func New(corezapcore.Core, options ...Option) *Logger

New constructs a new Logger from the provided zapcore.Core and Options. Ifthe passed zapcore.Core is nil, it falls back to using a no-opimplementation.

This is the most flexible way to construct a Logger, but also the mostverbose. For typical use cases, the highly-opinionated presets(NewProduction, NewDevelopment, and NewExample) or the Config struct aremore convenient.

For sample code, see the package-level AdvancedConfiguration example.

funcNewDevelopment

func NewDevelopment(options ...Option) (*Logger,error)

NewDevelopment builds a development Logger that writes DebugLevel and abovelogs to standard error in a human-friendly format.

It's a shortcut for NewDevelopmentConfig().Build(...Option).

funcNewExampleadded inv1.5.0

func NewExample(options ...Option) *Logger

NewExample builds a Logger that's designed for use in zap's testableexamples. It writes DebugLevel and above logs to standard out as JSON, butomits the timestamp and calling function to keep example outputshort and deterministic.

funcNewNop

func NewNop() *Logger

NewNop returns a no-op Logger. It never writes out logs or internal errors,and it never runs user-defined hooks.

Using WithOptions to replace the Core or error output of a no-op Logger canre-enable logging.

funcNewProduction

func NewProduction(options ...Option) (*Logger,error)

NewProduction builds a sensible production Logger that writes InfoLevel andabove logs to standard error as JSON.

It's a shortcut for NewProductionConfig().Build(...Option).

func (*Logger)Check

func (log *Logger) Check(lvlzapcore.Level, msgstring) *zapcore.CheckedEntry

Check returns a CheckedEntry if logging a message at the specified levelis enabled. It's a completely optional optimization; in high-performanceapplications, Check can help avoid allocating a slice to hold fields.

Example
package mainimport ("go.uber.org/zap")func main() {logger := zap.NewExample()defer logger.Sync()if ce := logger.Check(zap.DebugLevel, "debugging"); ce != nil {// If debug-level log output isn't enabled or if zap's sampling would have// dropped this log entry, we don't allocate the slice that holds these// fields.ce.Write(zap.String("foo", "bar"),zap.String("baz", "quux"),)}}
Output:{"level":"debug","msg":"debugging","foo":"bar","baz":"quux"}

func (*Logger)Core

func (log *Logger) Core()zapcore.Core

Core returns the Logger's underlying zapcore.Core.

func (*Logger)DPanic

func (log *Logger) DPanic(msgstring, fields ...Field)

DPanic logs a message at DPanicLevel. The message includes any fieldspassed 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 arerecoverable, but shouldn't ever happen.

func (*Logger)Debug

func (log *Logger) Debug(msgstring, fields ...Field)

Debug logs a message at DebugLevel. The message includes any fields passedat the log site, as well as any fields accumulated on the logger.

func (*Logger)Error

func (log *Logger) Error(msgstring, fields ...Field)

Error logs a message at ErrorLevel. The message includes any fields passedat the log site, as well as any fields accumulated on the logger.

func (*Logger)Fatal

func (log *Logger) Fatal(msgstring, fields ...Field)

Fatal logs a message at FatalLevel. The message includes any fields passedat the log site, as well as any fields accumulated on the logger.

The logger then calls os.Exit(1), even if logging at FatalLevel isdisabled.

func (*Logger)Info

func (log *Logger) Info(msgstring, fields ...Field)

Info logs a message at InfoLevel. The message includes any fields passedat the log site, as well as any fields accumulated on the logger.

func (*Logger)Leveladded inv1.24.0

func (log *Logger) Level()zapcore.Level

Level reports the minimum enabled level for this logger.

For NopLoggers, this iszapcore.InvalidLevel.

func (*Logger)Logadded inv1.22.0

func (log *Logger) Log(lvlzapcore.Level, msgstring, fields ...Field)

Log logs a message at the specified level. The message includes any fieldspassed at the log site, as well as any fields accumulated on the logger.Any Fields that require evaluation (such as Objects) are evaluated uponinvocation of Log.

func (*Logger)Nameadded inv1.25.0

func (log *Logger) Name()string

Name returns the Logger's underlying name,or an empty string if the logger is unnamed.

func (*Logger)Named

func (log *Logger) Named(sstring) *Logger

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

Example
package mainimport ("go.uber.org/zap")func main() {logger := zap.NewExample()defer logger.Sync()// By default, Loggers are unnamed.logger.Info("no name")// The first call to Named sets the Logger name.main := logger.Named("main")main.Info("main logger")// Additional calls to Named create a period-separated path.main.Named("subpackage").Info("sub-logger")}
Output:{"level":"info","msg":"no name"}{"level":"info","logger":"main","msg":"main logger"}{"level":"info","logger":"main.subpackage","msg":"sub-logger"}

func (*Logger)Panic

func (log *Logger) Panic(msgstring, fields ...Field)

Panic logs a message at PanicLevel. The message includes any fields passedat 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

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 asingle application to use both Loggers and SugaredLoggers, convertingbetween them on the boundaries of performance-sensitive code.

func (*Logger)Sync

func (log *Logger) Sync()error

Sync calls the underlying Core's Sync method, flushing any buffered logentries. Applications should take care to call Sync before exiting.

func (*Logger)Warn

func (log *Logger) Warn(msgstring, fields ...Field)

Warn logs a message at WarnLevel. The message includes any fields passedat the log site, as well as any fields accumulated on the logger.

func (*Logger)With

func (log *Logger) With(fields ...Field) *Logger

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

func (*Logger)WithLazyadded inv1.26.0

func (log *Logger) WithLazy(fields ...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 loggerswhen 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)WithOptions

func (log *Logger) WithOptions(opts ...Option) *Logger

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

typeObjectMarshalerPtradded inv1.24.0

type ObjectMarshalerPtr[Tany] interface {*Tzapcore.ObjectMarshaler}

ObjectMarshalerPtr is a constraint that specifies that the given typeimplements zapcore.ObjectMarshaler on a pointer receiver.

typeOption

type Option interface {// contains filtered or unexported methods}

An Option configures a Logger.

funcAddCaller

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.

funcAddCallerSkip

func AddCallerSkip(skipint)Option

AddCallerSkip increases the number of callers skipped by caller annotation(as enabled by the AddCaller option). When building wrappers around theLogger and SugaredLogger, supplying this Option prevents zap from alwaysreporting the wrapper code as the caller.

funcAddStacktrace

func AddStacktrace(lvlzapcore.LevelEnabler)Option

AddStacktrace configures the Logger to record a stack trace for all messages ator above a given level.

funcDevelopment

func Development()Option

Development puts the logger in development mode, which makes DPanic-levellogs panic instead of simply logging an error.

funcErrorOutput

func ErrorOutput(wzapcore.WriteSyncer)Option

ErrorOutput sets the destination for errors generated by the Logger. Notethat this option only affects internal errors; for sample code that sendserror-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 andzapcore.Lock functions are the simplest ways to protect files with a mutex.

funcFields

func Fields(fs ...Field)Option

Fields adds fields to the Logger.

funcHooks

func Hooks(hooks ...func(zapcore.Entry)error)Option

Hooks registers functions which will be called each time the Logger writesout an Entry. Repeated use of Hooks is additive.

Hooks are useful for simple side effects, like capturing metrics for thenumber of emitted logs. More complex side effects, including anything thatrequires access to the Entry's structured fields, should be implemented asa zapcore.Core instead. See zapcore.RegisterHooks for details.

funcIncreaseLeveladded inv1.14.0

func IncreaseLevel(lvlzapcore.LevelEnabler)Option

IncreaseLevel increase the level of the logger. It has no effect ifthe passed in level tries to decrease the level of the logger.

funcOnFataldeprecatedadded inv1.16.0

func OnFatal(actionzapcore.CheckWriteAction)Option

OnFatal sets the action to take on fatal logs.

Deprecated: UseWithFatalHook instead.

funcWithCalleradded inv1.15.0

func WithCaller(enabledbool)Option

WithCaller configures the Logger to annotate each message with the filename,line number, and function name of zap's caller, or not, depending on thevalue of enabled. This is a generalized form of AddCaller.

funcWithClockadded inv1.18.0

func WithClock(clockzapcore.Clock)Option

WithClock specifies the clock used by the logger to determine the currenttime for logged entries. Defaults to the system clock with time.Now.

funcWithFatalHookadded inv1.22.0

func WithFatalHook(hookzapcore.CheckWriteHook)Option

WithFatalHook sets a CheckWriteHook to run on fatal logs.Zap will call this hook after writing a log statement with a Fatal level.

For example, the following builds a logger that will exit the currentgoroutine after writing a fatal log message, but it will not exit theprogram.

zap.New(core, zap.WithFatalHook(zapcore.WriteThenGoexit))

It is important that the provided CheckWriteHook stops the control flow atthe current statement to meet expectations of callers of the logger.We recommend calling os.Exit or runtime.Goexit inside custom hooks atminimum.

funcWithPanicHookadded inv1.27.0

func WithPanicHook(hookzapcore.CheckWriteHook)Option

WithPanicHook sets a CheckWriteHook to run on Panic/DPanic logs.Zap will call this hook after writing a log statement with a Panic/DPanic level.

For example, the following builds a logger that will exit the currentgoroutine after writing a Panic/DPanic log message, but it will not start a panic.

zap.New(core, zap.WithPanicHook(zapcore.WriteThenGoexit))

This is useful for testing Panic/DPanic log output.

funcWrapCore

func WrapCore(f func(zapcore.Core)zapcore.Core)Option

WrapCore wraps or replaces the Logger's underlying zapcore.Core.

Example (Replace)
package mainimport ("go.uber.org/zap""go.uber.org/zap/zapcore")func main() {// Replacing a Logger's core can alter fundamental behaviors.// For example, it can convert a Logger to a no-op.nop := zap.WrapCore(func(zapcore.Core) zapcore.Core {return zapcore.NewNopCore()})logger := zap.NewExample()defer logger.Sync()logger.Info("working")logger.WithOptions(nop).Info("no-op")logger.Info("original logger still works")}
Output:{"level":"info","msg":"working"}{"level":"info","msg":"original logger still works"}

Example (Wrap)
package mainimport ("go.uber.org/zap""go.uber.org/zap/zapcore")func main() {// Wrapping a Logger's core can extend its functionality. As a trivial// example, it can double-write all logs.doubled := zap.WrapCore(func(c zapcore.Core) zapcore.Core {return zapcore.NewTee(c, c)})logger := zap.NewExample()defer logger.Sync()logger.Info("single")logger.WithOptions(doubled).Info("doubled")}
Output:{"level":"info","msg":"single"}{"level":"info","msg":"doubled"}{"level":"info","msg":"doubled"}

typeSamplingConfig

type SamplingConfig struct {Initialint                                           `json:"initial" yaml:"initial"`Thereafterint                                           `json:"thereafter" yaml:"thereafter"`Hook       func(zapcore.Entry,zapcore.SamplingDecision) `json:"-" yaml:"-"`}

SamplingConfig sets a sampling strategy for the logger. Sampling caps theglobal CPU and I/O load that logging puts on your process while attemptingto 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 zapcore.NewSamplerWithOptions fordetails.

typeSinkadded inv1.9.0

type Sink interface {zapcore.WriteSyncerio.Closer}

Sink defines the interface to write to and close logger destinations.

typeSugaredLogger

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

A SugaredLogger wraps the base Logger functionality in a slower, but lessverbose, API. Any Logger can be converted to a SugaredLogger with its Sugarmethod.

Unlike the Logger, the SugaredLogger doesn't insist on structured logging.For each log level, it exposes four methods:

  • methods named after the log level for log.Print-style logging
  • methods ending in "w" for loosely-typed structured logging
  • methods ending in "f" for log.Printf-style logging
  • methods ending in "ln" for log.Println-style logging

For example, the methods for InfoLevel are:

Info(...any)           Print-style loggingInfow(...any)          Structured logging (read as "info with")Infof(string, ...any)  Printf-style loggingInfoln(...any)         Println-style logging

funcS

func S() *SugaredLogger

S returns the global SugaredLogger, which can be reconfigured withReplaceGlobals. It's safe for concurrent use.

func (*SugaredLogger)DPanic

func (s *SugaredLogger) DPanic(args ...interface{})

DPanic logs the provided arguments atDPanicLevel.In development, the logger then panics. (SeeDPanicLevel for details.)Spaces are added between arguments when neither is a string.

func (*SugaredLogger)DPanicf

func (s *SugaredLogger) DPanicf(templatestring, args ...interface{})

DPanicf formats the message according to the format specifierand logs it atDPanicLevel.In development, the logger then panics. (SeeDPanicLevel for details.)

func (*SugaredLogger)DPaniclnadded inv1.22.0

func (s *SugaredLogger) DPanicln(args ...interface{})

DPanicln logs a message atDPanicLevel.In development, the logger then panics. (SeeDPanicLevel for details.)Spaces are always added between arguments.

func (*SugaredLogger)DPanicw

func (s *SugaredLogger) DPanicw(msgstring, keysAndValues ...interface{})

DPanicw logs a message with some additional context. In development, thelogger then panics. (See DPanicLevel for details.) The variadic key-valuepairs are treated as they are in With.

func (*SugaredLogger)Debug

func (s *SugaredLogger) Debug(args ...interface{})

Debug logs the provided arguments atDebugLevel.Spaces are added between arguments when neither is a string.

func (*SugaredLogger)Debugf

func (s *SugaredLogger) Debugf(templatestring, args ...interface{})

Debugf formats the message according to the format specifierand logs it atDebugLevel.

func (*SugaredLogger)Debuglnadded inv1.22.0

func (s *SugaredLogger) Debugln(args ...interface{})

Debugln logs a message atDebugLevel.Spaces are always added between arguments.

func (*SugaredLogger)Debugw

func (s *SugaredLogger) Debugw(msgstring, keysAndValues ...interface{})

Debugw logs a message with some additional context. The variadic key-valuepairs are treated as they are in With.

When debug-level logging is disabled, this is much faster than

s.With(keysAndValues).Debug(msg)

func (*SugaredLogger)Desugar

func (s *SugaredLogger) Desugar() *Logger

Desugar unwraps a SugaredLogger, exposing the original Logger. Desugaringis quite inexpensive, so it's reasonable for a single application to useboth Loggers and SugaredLoggers, converting between them on the boundariesof performance-sensitive code.

func (*SugaredLogger)Error

func (s *SugaredLogger) Error(args ...interface{})

Error logs the provided arguments atErrorLevel.Spaces are added between arguments when neither is a string.

func (*SugaredLogger)Errorf

func (s *SugaredLogger) Errorf(templatestring, args ...interface{})

Errorf formats the message according to the format specifierand logs it atErrorLevel.

func (*SugaredLogger)Errorlnadded inv1.22.0

func (s *SugaredLogger) Errorln(args ...interface{})

Errorln logs a message atErrorLevel.Spaces are always added between arguments.

func (*SugaredLogger)Errorw

func (s *SugaredLogger) Errorw(msgstring, keysAndValues ...interface{})

Errorw logs a message with some additional context. The variadic key-valuepairs are treated as they are in With.

func (*SugaredLogger)Fatal

func (s *SugaredLogger) Fatal(args ...interface{})

Fatal constructs a message with the provided arguments and calls os.Exit.Spaces are added between arguments when neither is a string.

func (*SugaredLogger)Fatalf

func (s *SugaredLogger) Fatalf(templatestring, args ...interface{})

Fatalf formats the message according to the format specifierand calls os.Exit.

func (*SugaredLogger)Fatallnadded inv1.22.0

func (s *SugaredLogger) Fatalln(args ...interface{})

Fatalln logs a message atFatalLevel and calls os.Exit.Spaces are always added between arguments.

func (*SugaredLogger)Fatalw

func (s *SugaredLogger) Fatalw(msgstring, keysAndValues ...interface{})

Fatalw logs a message with some additional context, then calls os.Exit. Thevariadic key-value pairs are treated as they are in With.

func (*SugaredLogger)Info

func (s *SugaredLogger) Info(args ...interface{})

Info logs the provided arguments atInfoLevel.Spaces are added between arguments when neither is a string.

func (*SugaredLogger)Infof

func (s *SugaredLogger) Infof(templatestring, args ...interface{})

Infof formats the message according to the format specifierand logs it atInfoLevel.

func (*SugaredLogger)Infolnadded inv1.22.0

func (s *SugaredLogger) Infoln(args ...interface{})

Infoln logs a message atInfoLevel.Spaces are always added between arguments.

func (*SugaredLogger)Infow

func (s *SugaredLogger) Infow(msgstring, keysAndValues ...interface{})

Infow logs a message with some additional context. The variadic key-valuepairs are treated as they are in With.

func (*SugaredLogger)Leveladded inv1.24.0

func (s *SugaredLogger) Level()zapcore.Level

Level reports the minimum enabled level for this logger.

For NopLoggers, this iszapcore.InvalidLevel.

func (*SugaredLogger)Logadded inv1.27.0

func (s *SugaredLogger) Log(lvlzapcore.Level, args ...interface{})

Log logs the provided arguments at provided level.Spaces are added between arguments when neither is a string.

func (*SugaredLogger)Logfadded inv1.27.0

func (s *SugaredLogger) Logf(lvlzapcore.Level, templatestring, args ...interface{})

Logf formats the message according to the format specifierand logs it at provided level.

func (*SugaredLogger)Loglnadded inv1.27.0

func (s *SugaredLogger) Logln(lvlzapcore.Level, args ...interface{})

Logln logs a message at provided level.Spaces are always added between arguments.

func (*SugaredLogger)Logwadded inv1.27.0

func (s *SugaredLogger) Logw(lvlzapcore.Level, msgstring, keysAndValues ...interface{})

Logw logs a message with some additional context. The variadic key-valuepairs are treated as they are in With.

func (*SugaredLogger)Named

func (s *SugaredLogger) Named(namestring) *SugaredLogger

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

func (*SugaredLogger)Panic

func (s *SugaredLogger) Panic(args ...interface{})

Panic constructs a message with the provided arguments and panics.Spaces are added between arguments when neither is a string.

func (*SugaredLogger)Panicf

func (s *SugaredLogger) Panicf(templatestring, args ...interface{})

Panicf formats the message according to the format specifierand panics.

func (*SugaredLogger)Paniclnadded inv1.22.0

func (s *SugaredLogger) Panicln(args ...interface{})

Panicln logs a message atPanicLevel and panics.Spaces are always added between arguments.

func (*SugaredLogger)Panicw

func (s *SugaredLogger) Panicw(msgstring, keysAndValues ...interface{})

Panicw logs a message with some additional context, then panics. Thevariadic key-value pairs are treated as they are in With.

func (*SugaredLogger)Sync

func (s *SugaredLogger) Sync()error

Sync flushes any buffered log entries.

func (*SugaredLogger)Warn

func (s *SugaredLogger) Warn(args ...interface{})

Warn logs the provided arguments atWarnLevel.Spaces are added between arguments when neither is a string.

func (*SugaredLogger)Warnf

func (s *SugaredLogger) Warnf(templatestring, args ...interface{})

Warnf formats the message according to the format specifierand logs it atWarnLevel.

func (*SugaredLogger)Warnlnadded inv1.22.0

func (s *SugaredLogger) Warnln(args ...interface{})

Warnln logs a message atWarnLevel.Spaces are always added between arguments.

func (*SugaredLogger)Warnw

func (s *SugaredLogger) Warnw(msgstring, keysAndValues ...interface{})

Warnw logs a message with some additional context. The variadic key-valuepairs are treated as they are in With.

func (*SugaredLogger)With

func (s *SugaredLogger) With(args ...interface{}) *SugaredLogger

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

For example,

 sugaredLogger.With(   "hello", "world",   "failure", errors.New("oh no"),   Stack(),   "count", 42,   "user", User{Name: "alice"},)

is the equivalent of

unsugared.With(  String("hello", "world"),  String("failure", "oh no"),  Stack(),  Int("count", 42),  Object("user", User{Name: "alice"}),)

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

func (*SugaredLogger)WithLazyadded inv1.27.0

func (s *SugaredLogger) WithLazy(args ...interface{}) *SugaredLogger

WithLazy adds a variadic number of fields to the logging context 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().

Similar to [With], fields added to the child don't affect the parent,and vice versa. Also, the keys in key-value pairs should be strings. In development,passing a non-string key panics, while in production it logs an error and skips the pair.Passing an orphaned key has the same behavior.

func (*SugaredLogger)WithOptionsadded inv1.22.0

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

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

Source Files

View all Source files

Directories

PathSynopsis
Package buffer provides a thin wrapper around a byte slice.
Package buffer provides a thin wrapper around a byte slice.
expmodule
Package internal and its subpackages hold types and functionality that are not part of Zap's public API.
Package internal and its subpackages hold types and functionality that are not part of Zap's public API.
bufferpool
Package bufferpool houses zap's shared internal buffer pool.
Package bufferpool houses zap's shared internal buffer pool.
color
Package color adds coloring functionality for TTY output.
Package color adds coloring functionality for TTY output.
exit
Package exit provides stubs so that unit tests can exercise code that calls os.Exit(1).
Package exit provides stubs so that unit tests can exercise code that calls os.Exit(1).
pool
Package pool provides internal pool utilities.
Package pool provides internal pool utilities.
readmecommand
readme generates Zap's README from a template.
readme generates Zap's README from a template.
stacktrace
Package stacktrace provides support for gathering stack traces efficiently.
Package stacktrace provides support for gathering stack traces efficiently.
ztest
Package ztest provides low-level helpers for testing log output.
Package ztest provides low-level helpers for testing log output.
Package zapcore defines and implements the low-level interfaces upon which zap is built.
Package zapcore defines and implements the low-level interfaces upon which zap is built.
Package zapgrpc provides a logger that is compatible with grpclog.
Package zapgrpc provides a logger that is compatible with grpclog.
Package zapio provides tools for interacting with IO streams through Zap.
Package zapio provides tools for interacting with IO streams through Zap.
Package zaptest provides a variety of helpers for testing log output.
Package zaptest provides a variety of helpers for testing log output.
observer
Package observer provides a zapcore.Core that keeps an in-memory, encoding-agnostic representation of log entries.
Package observer provides a zapcore.Core that keeps an in-memory, encoding-agnostic representation of log entries.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp