Zero Allocation JSON Logger - High-performance structured logging library for Go
npx @tessl/cli install tessl/golang-github-com-rs-zerolog@1.34.0Zerolog is a zero-allocation JSON logger for Go that provides fast, structured logging with a chainable API. It's designed for high-performance applications where logging overhead matters.
Name: github.com/rs/zerolog
Type: Logging Library
Language: Go
Version: 1.34.0
go get -u github.com/rs/zerologimport "github.com/rs/zerolog"
import "github.com/rs/zerolog/log" // Optional: global logger convenience packageimport "github.com/rs/zerolog/log"
log.Info().Msg("hello world")
// Output: {"level":"info","time":"2024-01-15T10:30:00Z","message":"hello world"}import (
"os"
"github.com/rs/zerolog"
)
logger := zerolog.New(os.Stderr).With().Timestamp().Logger()
logger.Info().
Str("foo", "bar").
Int("count", 42).
Msg("hello world")
// Output: {"level":"info","time":1494567715,"foo":"bar","count":42,"message":"hello world"}// Create child logger with persistent context
sublogger := logger.With().
Str("component", "database").
Str("service", "api").
Logger()
sublogger.Info().Msg("connection established")
// Output includes "component":"database" and "service":"api" automaticallyerr := errors.New("connection failed")
logger.Error().
Err(err).
Str("host", "localhost").
Int("port", 5432).
Msg("database connection error")Zerolog is organized around several core types:
SyncWriter and lock-free diode.Writer// Create root logger
func New(w io.Writer) Logger
// Create disabled logger (no-op)
func Nop() Loggerfunc (l Logger) Debug() *Event
func (l Logger) Info() *Event
func (l Logger) Warn() *Event
func (l Logger) Error() *Event
func (l Logger) Fatal() *Event // Calls os.Exit(1) after logging
func (l Logger) Panic() *Event // Calls panic() after logging
func (l Logger) Trace() *Event
func (l Logger) Log() *Event // No levelfunc (e *Event) Msg(msg string)
func (e *Event) Msgf(format string, v ...interface{})
func (e *Event) Send() // No messagefunc (e *Event) Str(key, val string) *Event
func (e *Event) Int(key string, i int) *Event
func (e *Event) Bool(key string, b bool) *Event
func (e *Event) Time(key string, t time.Time) *Event
func (e *Event) Dur(key string, d time.Duration) *Event
func (e *Event) Err(err error) *Event
func (e *Event) Interface(key string, i interface{}) *EventThe foundation of zerolog with Logger, Event, and Level types. Learn how to create loggers, emit events at different levels, and control output.
Err() methodView Core Logging Documentation →
Build child loggers with persistent fields that appear in all subsequent log events. Perfect for adding request IDs, user IDs, or component names.
With()context.ContextView Contextual Logging Documentation →
Complete reference of all strongly-typed field methods for adding data to log events. Zerolog provides methods for all Go primitive types, time values, network types, and more.
Str(), Strs(), Stringer()Int(), Float64(), Uint() and variantsTime(), Dur(), TimeDiff(), Timestamp()Bytes(), Hex(), RawJSON()IPAddr(), MACAddr(), IPPrefix()View Field Methods Reference →
Writers control where and how logs are written. Zerolog includes several writer implementations and adapters for different output strategies.
ConsoleWriter - Human-friendly, colorized output for developmentLevelWriter - Route different log levels to different destinationsMultiLevelWriter - Write to multiple outputs simultaneouslySyncWriter - Thread-safe writer wrapperFilteredLevelWriter - Filter by minimum levelTriggerLevelWriter - Buffer until trigger conditionView Writers and Output Documentation →
Reduce log volume by sampling events. Samplers determine which events get logged based on frequency, probability, or level.
BasicSampler - Log every Nth eventRandomSampler - Probabilistic samplingBurstSampler - Allow burst then sampleLevelSampler - Different sampling per levelHooks intercept log events before they're written, allowing you to modify, enrich, or filter events.
HookFunc - Function adapterLevelHook - Different hooks per levelComplex data structures for logging nested objects, arrays, and custom types.
Array - Pre-built arrays for log eventsDict() - Nested dictionariesLogObjectMarshaler - Custom object marshaling interfaceLogArrayMarshaler - Custom array marshaling interfaceEmbedObject()View Advanced Types Documentation →
Global variables and settings that affect all loggers. Customize field names, time formats, marshalers, and more.
TimestampFieldName, LevelFieldName, etc.)LevelInfoValue, LevelErrorValue, etc.)SetGlobalLevel()View Global Configuration Documentation →
The log subpackage provides a global logger with convenience functions for quick logging without creating logger instances.
Logger instancelog.Info(), log.Error(), etc.log.With(), log.Ctx()View Global Logger Documentation →
The hlog subpackage provides HTTP middleware for request logging with automatic request metadata capture.
http.Handler middleware patternView HTTP Middleware Documentation →
The diode subpackage provides a non-blocking, lock-free writer implementation using a ring buffer (diode pattern).
View Diode Writer Documentation →
The pkgerrors subpackage integrates with github.com/pkg/errors to extract and log stack traces from wrapped errors.
pkg/errors error wrappingErrorStackMarshalerView Package Errors Integration →
The journald subpackage provides integration with systemd journal for structured logging on Linux systems.
View Journald Integration Documentation →
TraceLevel Level = -1 // Finest-grained logs
DebugLevel Level = 0 // Debug information
InfoLevel Level = 1 // General information
WarnLevel Level = 2 // Warning messages
ErrorLevel Level = 3 // Error conditions
FatalLevel Level = 4 // Fatal errors (calls os.Exit)
PanicLevel Level = 5 // Panic conditions (calls panic)
NoLevel Level = 6 // No level
Disabled Level = 7 // Disabled loggingSet Global Minimum Level:
zerolog.SetGlobalLevel(zerolog.InfoLevel)Pretty Console Logging:
logger := zerolog.New(zerolog.ConsoleWriter{Out: os.Stderr}).
With().Timestamp().Logger()Thread-Safe Logging:
logger := zerolog.New(zerolog.SyncWriter(os.Stderr)).
With().Timestamp().Logger()Conditional Logging:
if e := logger.Debug(); e.Enabled() {
// Expensive computation only if debug enabled
value := computeExpensiveValue()
e.Str("result", value).Msg("debug info")
}Zerolog is designed for minimal overhead:
diode.WriterZerolog loggers are not thread-safe by default. For concurrent access:
zerolog.SyncWriter() for mutex-based safetydiode.Writer() for lock-free non-blocking writesUpdateContext() are not safe