Categorygithub.com/n-r-w/ctxlog
modulepackage
1.0.3
Repository: https://github.com/n-r-w/ctxlog.git
Documentation: pkg.go.dev

# README

CTXLog

A context-aware structured logging package for Go that provides a robust wrapper around log/slog with enhanced functionality and configuration options. Under the hood, it uses go.uber.org/zap as the logging backend for optimal performance and reliability.

Go Reference CI Status Go Report Card

Package Overview

CTXLog is designed to simplify structured logging in Go applications by providing context-aware logging capabilities with support for both development and production environments. It seamlessly integrates with Go's standard log/slog package while adding powerful features like context propagation, sampling, and OpenTelemetry integration. The package leverages go.uber.org/zap as its logging backend, combining the convenience of slog's interface with Zap's high-performance logging capabilities.

Key Features

  • Context-aware logging with automatic context propagation
  • Support for both development (human-readable) and production (JSON) logging formats
  • Automatic source code location (file and line number) tracking
  • Log sampling capabilities for high-throughput applications
  • OpenTelemetry integration
  • Built-in test logging support
  • Error logging with automatic stack traces
  • Convenient helper functions for common logging patterns
  • Group-based logging for better organization
  • High-performance logging through Zap backend

Configuration Options

The logger can be configured using the following options:

Environment Mode

  • WithEnvType(): Sets the logger environment mode
    • EnvDevelopment: Human-readable logs for development
    • EnvProduction: JSON logs for production (default)

Log Level and Source

  • WithLevel(level slog.Leveler): Sets the minimum logging level
  • WithSource(bool): Adds file name and line number to log records

Identification

  • WithName(name string): Sets the logger name

Sampling

  • WithSampler(tick time.Duration, first, thereafter int): Configures log sampling
    • tick: Sampling interval
    • first: Number of entries to log during the interval
    • thereafter: Number of entries to log after the initial entries

Integration

  • WithOtelTracing(): Enables OpenTelemetry integration
  • WithTesting(t testing.TB): Configures logger for use in tests

Installation

go get github.com/n-r-w/ctxlog

Usage Examples

See example/main.go for comprehensive usage examples, including:

  • Basic logger setup with production mode and debug level
  • Context propagation and extraction
  • Structured logging with various field types
  • Group-based logging
  • Error handling with automatic stack traces
  • Working with context-bound loggers

The example demonstrates all major features and provides a practical reference for integrating CTXLog into your application.

ILogger Interface

ILogger is a logger interface to extract the logger implementation from the project to external dependencies.

This package contains two implementations of the ctxlog.ILogger interface:

  • ctxlog.NewWrapper - allows wrapping ctxlog.Logger in this interface.
  • ctxlog.NewStubWrapper - fake logging. It does not do anything.

# Packages

nolint:mnd // ok for example.

# Functions

CloseError closes c, logging any error that occurs.
Debug logs a message at Debug level.
EnvTypeFromString returns the EnvType for a string.
Error logs a message at Error level.
FromContext returns the logger from the context.
GetSkipCallStack returns the number of stack frames to skip when logging.
InContext returns true if the context has a logger.
Info logs a message at Info level.
Log logs a message at the specified level.
LogWithLevel logs a message at the specified level and stack frame skip.
Must panics if the logger cannot be created.
MustContext returns a new context with the logger.
New creates a new logger.
NewContext returns a new context with the logger.
NewMockILogger creates a new mock instance.
NewStubWrapper returns a new stub wrapper that implements the ILogger interface and does nothing.
NewWrapper returns a new wrapper that implements the ILogger interface.
SetSkipCallStack sets the number of stack frames to skip when logging.
Sync synchronizes logging in the context.
ToContext adds a logger to the context.
ToContextFromContext extracts the logger from ctxWithLogger and adds it to targetCtx.
ToTestContext returns a context where logs will be written to testing.TB.
TryFromContext attempts to get a logger from the context.
Warn logs a message at Warn level.
With returns a logger that includes the specified attributes.
WithEnvType sets the logger environment mode.
WithGroup returns a logger that starts a group if name is not empty.
WithLevel sets the minimum logging level.
WithName adds a name to logger output.
WithOtelTracing sets up the logger to use OpenTelemetry.
WithSampler sets the sampler for the logger.
WithSource adds the file name and line number of the call to the log record.
WithTestBuffer sets a buffer for capturing test output.
WithTesting sets up the logger for use in tests.
WithTimeLayout sets the time layout for the logger.

# Constants

EnvDevelopment (default) sets the logger to Development mode.
EnvProduction sets the logger to Production mode.

# Structs

Logger is a slog with zap backend.
MockILogger is a mock of ILogger interface.
MockILoggerMockRecorder is the mock recorder for MockILogger.

# Interfaces

ILogger is a logger interface to extract the logger implementation from the project to external dependencies.

# Type aliases

EnvType is a logger environment mode.
Option is a function for configuring the logger.