Socket
Socket
Sign inDemoInstall

go.uber.org/zap

Package Overview
Dependencies
7
Alerts
File Explorer

Install Socket

Detect and block malicious and high-risk dependencies

Install

    go.uber.org/zap

Package zap provides fast, structured, leveled logging. For applications that log in the hot path, reflection-based serialization and string formatting are prohibitively expensive - they're CPU-intensive and make many small allocations. Put differently, using json.Marshal and fmt.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 avoid serialization overhead and allocations wherever possible. By building the high-level SugaredLogger on that foundation, zap lets users choose when they need to count every allocation and when they'd prefer a more familiar, loosely typed API. In contexts where performance is nice, but not critical, use the SugaredLogger. It's 4-10x faster than other structured logging packages and supports both structured and printf-style logging. Like log15 and go-kit, the SugaredLogger's structured logging APIs are loosely typed and accept a variadic number of key-value pairs. (For more advanced use cases, they also accept strongly typed fields - see the SugaredLogger.With documentation for details.) By default, loggers are unbuffered. However, since zap's low-level APIs allow buffering, calling Sync before letting your process exit is a good habit. In the rare contexts where every microsecond and every allocation matter, use the Logger. It's even faster than the SugaredLogger and allocates far less, but it only supports strongly-typed, structured logging. Choosing between the Logger and SugaredLogger doesn't need to be an application-wide decision: converting between the two is simple and inexpensive. The simplest way to build a Logger is to use zap's opinionated presets: NewExample, NewProduction, and NewDevelopment. These presets build a logger with a single function call: Presets are fine for small projects, but larger projects and organizations naturally require a bit more customization. For most users, zap's Config struct strikes the right balance between flexibility and convenience. See the package-level BasicConfiguration example for sample code. More unusual configurations (splitting output between files, sending logs to a message queue, etc.) are possible, but require direct use of go.uber.org/zap/zapcore. See the package-level AdvancedConfiguration example for sample code. The zap package itself is a relatively thin wrapper around the interfaces in 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 an exception aggregation service, like Sentry or Rollbar) typically requires implementing the zapcore.Encoder, zapcore.WriteSyncer, or zapcore.Core interfaces. See the zapcore documentation for details. Similarly, package authors can use the high-performance Encoder and Core implementations in the zapcore package to build their own loggers. An FAQ covering everything from installation errors to design decisions is available at https://github.com/uber-go/zap/blob/master/FAQ.md.


Version published

Readme

Source

:zap: zap

Blazing fast, structured, leveled logging in Go.

Zap logo

GoDoc Build Status Coverage 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 the SugaredLogger. It's 4-10x faster than other structured logging packages and includes both structured and printf-style APIs.

logger, _ := zap.NewProduction()
defer logger.Sync() // flushes buffer, if any
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)

When performance and type safety are critical, use the Logger. It's even faster than the SugaredLogger and allocates far less, but it only supports structured 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 the documentation and FAQ for more details.

Performance

For applications that log in the hot path, reflection-based serialization and string formatting are prohibitively expensive — they're CPU-intensive and make many small allocations. Put differently, using encoding/json and fmt.Fprintf to log tons of interface{}s makes your application slow.

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

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

Log a message and 10 fields:

PackageTimeTime % to zapObjects Allocated
:zap: zap656 ns/op+0%5 allocs/op
:zap: 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
:zap: zap67 ns/op+0%0 allocs/op
:zap: 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 or printf-style templating:

PackageTimeTime % to zapObjects Allocated
:zap: zap63 ns/op+0%0 allocs/op
:zap: 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 series of releases. Users of semver-aware dependency management systems should pin zap to ^1.

Contributing

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


Released under the MIT License.

1 In particular, keep in mind that we may be benchmarking against slightly older versions of other packages. Versions are pinned in the benchmarks/go.mod file.

FAQs

Last updated on 20 Feb 2024

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc