CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/golang-github-com-rs-zerolog

Zero Allocation JSON Logger - High-performance structured logging library for Go

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Zerolog

Zerolog 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.

Package Information

Name: github.com/rs/zerolog Type: Logging Library Language: Go Version: 1.34.0

Installation

go get -u github.com/rs/zerolog

Core Imports

import "github.com/rs/zerolog"
import "github.com/rs/zerolog/log"  // Optional: global logger convenience package

Basic Usage

Simple Logging with Global Logger

import "github.com/rs/zerolog/log"

log.Info().Msg("hello world")
// Output: {"level":"info","time":"2024-01-15T10:30:00Z","message":"hello world"}

Creating a Logger Instance

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"}

Adding Contextual Fields

// 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" automatically

Error Logging

err := errors.New("connection failed")

logger.Error().
    Err(err).
    Str("host", "localhost").
    Int("port", 5432).
    Msg("database connection error")

Architecture Overview

Key Components

Zerolog is organized around several core types:

  1. Logger - The main logging object that creates log events
  2. Event - Represents a single log event with chainable field methods
  3. Context - Builds loggers with contextual fields that persist across events
  4. Level - Log level enumeration (Trace, Debug, Info, Warn, Error, Fatal, Panic)
  5. Writers - Output destinations including console, level-based routing, and more
  6. Samplers - Control which events get logged based on frequency or level
  7. Hooks - Intercept and modify log events before they're written

Design Principles

  • Zero Allocation: Event pooling and careful memory management avoid allocations in the hot path
  • Chaining API: Fluent interface for adding fields and configuring loggers
  • Lazy Evaluation: Fields are only evaluated if the event will be logged
  • Structured Logging: Native JSON output with strongly-typed fields
  • Thread Safety: Multiple options including SyncWriter and lock-free diode.Writer

Core API

Logger Creation

// Create root logger
func New(w io.Writer) Logger

// Create disabled logger (no-op)
func Nop() Logger

Level Methods

func (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 level

Event Termination

func (e *Event) Msg(msg string)
func (e *Event) Msgf(format string, v ...interface{})
func (e *Event) Send()  // No message

Common Field Methods

func (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{}) *Event

Capabilities

Core Logging

The foundation of zerolog with Logger, Event, and Level types. Learn how to create loggers, emit events at different levels, and control output.

  • Log levels: Trace, Debug, Info, Warn, Error, Fatal, Panic
  • Logger configuration: minimum level, output writers
  • Event lifecycle and termination
  • Special error handling with Err() method

View Core Logging Documentation →

Contextual Logging

Build child loggers with persistent fields that appear in all subsequent log events. Perfect for adding request IDs, user IDs, or component names.

  • Creating child loggers with With()
  • Context field methods
  • Updating logger context
  • Context integration with Go's context.Context

View Contextual Logging Documentation →

Field Methods

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.

  • String fields: Str(), Strs(), Stringer()
  • Numeric fields: Int(), Float64(), Uint() and variants
  • Time fields: Time(), Dur(), TimeDiff(), Timestamp()
  • Binary fields: Bytes(), Hex(), RawJSON()
  • Network fields: IPAddr(), MACAddr(), IPPrefix()
  • Array and slice fields for all types

View Field Methods Reference →

Writers and Output

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 development
  • LevelWriter - Route different log levels to different destinations
  • MultiLevelWriter - Write to multiple outputs simultaneously
  • SyncWriter - Thread-safe writer wrapper
  • FilteredLevelWriter - Filter by minimum level
  • TriggerLevelWriter - Buffer until trigger condition

View Writers and Output Documentation →

Sampling

Reduce log volume by sampling events. Samplers determine which events get logged based on frequency, probability, or level.

  • BasicSampler - Log every Nth event
  • RandomSampler - Probabilistic sampling
  • BurstSampler - Allow burst then sample
  • LevelSampler - Different sampling per level

View Sampling Documentation →

Hooks

Hooks intercept log events before they're written, allowing you to modify, enrich, or filter events.

  • Hook interface
  • HookFunc - Function adapter
  • LevelHook - Different hooks per level
  • Common use cases: adding cloud trace IDs, filtering sensitive data

View Hooks Documentation →

Advanced Types

Complex data structures for logging nested objects, arrays, and custom types.

  • Array - Pre-built arrays for log events
  • Dict() - Nested dictionaries
  • LogObjectMarshaler - Custom object marshaling interface
  • LogArrayMarshaler - Custom array marshaling interface
  • Embedding objects with EmbedObject()

View Advanced Types Documentation →

Global Configuration

Global variables and settings that affect all loggers. Customize field names, time formats, marshalers, and more.

  • Field name configuration (TimestampFieldName, LevelFieldName, etc.)
  • Level string values (LevelInfoValue, LevelErrorValue, etc.)
  • Time and duration formatting
  • Custom marshalers for errors, interfaces, and more
  • Global level setting with SetGlobalLevel()

View Global Configuration Documentation →

Global Logger

The log subpackage provides a global logger with convenience functions for quick logging without creating logger instances.

  • Pre-configured global Logger instance
  • Convenience functions: log.Info(), log.Error(), etc.
  • Context functions: log.With(), log.Ctx()
  • Perfect for simple applications and quick debugging

View Global Logger Documentation →

HTTP Middleware

The hlog subpackage provides HTTP middleware for request logging with automatic request metadata capture.

  • Logger injection into request context
  • Request ID generation and tracking
  • Access logging with status, size, duration
  • Metadata handlers: URL, method, user agent, remote IP, etc.
  • Standard Go http.Handler middleware pattern

View HTTP Middleware Documentation →

Diode Writer

The diode subpackage provides a non-blocking, lock-free writer implementation using a ring buffer (diode pattern).

  • Non-blocking writes
  • Configurable ring buffer size
  • Alert callback for dropped messages
  • Perfect for high-throughput applications
  • Zero lock contention

View Diode Writer Documentation →

Package Errors Integration

The pkgerrors subpackage integrates with github.com/pkg/errors to extract and log stack traces from wrapped errors.

  • Automatic stack trace extraction
  • Compatible with pkg/errors error wrapping
  • Configurable stack frame field names
  • Integration with ErrorStackMarshaler

View Package Errors Integration →

Journald Integration

The journald subpackage provides integration with systemd journal for structured logging on Linux systems.

  • Direct systemd journal logging
  • Structured field support
  • Native Linux system integration
  • Zero dependencies (uses Unix sockets)

View Journald Integration Documentation →

Quick Reference

Log Levels

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 logging

Common Patterns

Set 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")
}

Performance

Zerolog is designed for minimal overhead:

  • Zero allocations in the hot path (event pooling)
  • Lazy field evaluation (skipped if event disabled)
  • Efficient JSON encoding
  • Optional non-blocking writes with diode.Writer
  • Sampling to reduce high-volume logs

Thread Safety

Zerolog loggers are not thread-safe by default. For concurrent access:

  • Use zerolog.SyncWriter() for mutex-based safety
  • Use diode.Writer() for lock-free non-blocking writes
  • Create separate logger instances per goroutine
  • Context updates via UpdateContext() are not safe

See Also

  • GitHub Repository
  • Go Package Documentation
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
golangpkg:golang/github.com/rs/zerolog@v1.34.0
Publish Source
CLI
Badge
tessl/golang-github-com-rs-zerolog badge