Skip to content

Release v0.5.3 - Error Handling & Logging

Choose a tag to compare

@thanos thanos released this 22 Oct 02:18
· 11 commits to main since this release
cb3a8c1

Release Date: October 18, 2025

Overview

Version 0.5.3 introduces comprehensive Error Handling & Logging capabilities, providing detailed error context information, custom logging callbacks, and configurable log levels. This release significantly enhances debugging and monitoring capabilities for production applications.

New Features

🔍 Error Context (#143)

  • Detailed Error Information: Rich error context with operation details, keys, collections, and metadata
  • Structured Error Data: Comprehensive error information including timestamps, status codes, and descriptions
  • Memory Management: Automatic cleanup of error context data structures
  • libcouchbase Integration: Direct mapping from libcouchbase status codes to Zig error types

📝 Custom Logging (#144)

  • User-Defined Callbacks: Custom logging functions for specialized log handling
  • Flexible Output: Support for file logging, custom formatting, and external log systems
  • Structured Logging: Rich log entries with metadata, timestamps, and component information
  • Default Implementation: Built-in default logging to stderr

🎛️ Log Level Control (#145)

  • Configurable Levels: DEBUG, INFO, WARN, ERROR, FATAL log levels
  • Runtime Control: Dynamic log level adjustment during application execution
  • Filtering: Automatic filtering of log messages based on configured minimum level
  • Performance: Efficient log level checking to minimize overhead

API Reference

Error Context

// Create error context
var error_context = try client.createErrorContext(
    couchbase.Error.DocumentNotFound,
    "get",
    status_code,
);

// Add additional context
try error_context.withKey("user:123");
try error_context.withCollection("users", "default");
try error_context.addMetadata("retry_count", "3");

// Log with context
try client.logErrorWithContext("operations", "Document not found", &error_context);

Logging Configuration

// Configure logging
const logging_config = couchbase.LoggingConfig{
    .min_level = .debug,
    .callback = customLogCallback,
    .include_timestamps = true,
    .include_component = true,
    .include_metadata = true,
};

// Connect with logging
var client = try couchbase.Client.connect(allocator, .{
    .connection_string = "couchbase://127.0.0.1",
    .logging_config = logging_config,
});

Logging Methods

// Basic logging
try client.logDebug("component", "Debug message");
try client.logInfo("component", "Info message");
try client.logWarn("component", "Warning message");
try client.logError("component", "Error message");

// Dynamic log level control
client.setLogLevel(.warn);
client.setLogCallback(customCallback);

New Types

ErrorContext

  • err: Error - The primary error that occurred
  • operation: []const u8 - Operation that failed
  • key: ?[]const u8 - Document key involved
  • collection: ?[]const u8 - Collection context
  • scope: ?[]const u8 - Scope context
  • metadata: StringHashMap([]const u8) - Additional metadata
  • timestamp: u64 - When the error occurred
  • status_code: lcb_STATUS - libcouchbase status code
  • description: []const u8 - Error description

LogLevel

  • debug - Debug information
  • info - General information
  • warn - Warning messages
  • err - Error messages
  • fatal - Fatal errors

LoggingConfig

  • min_level: LogLevel - Minimum log level to output
  • callback: ?LogCallback - Custom logging callback
  • include_timestamps: bool - Include timestamps in logs
  • include_component: bool - Include component names
  • include_metadata: bool - Include metadata in logs

LogEntry

  • level: LogLevel - Log level
  • message: []const u8 - Log message
  • timestamp: u64 - Timestamp
  • component: []const u8 - Component that generated the log
  • error_context: ?*ErrorContext - Optional error context
  • metadata: StringHashMap([]const u8) - Additional metadata

Examples

Basic Error Handling

const std = @import("std");
const couchbase = @import("couchbase");

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    var client = try couchbase.Client.connect(allocator, .{
        .connection_string = "couchbase://127.0.0.1",
        .logging_config = .{ .min_level = .debug },
    });
    defer client.disconnect();

    // Log messages at different levels
    try client.logDebug("demo", "Debug information");
    try client.logInfo("demo", "Application started");
    try client.logWarn("demo", "Configuration warning");
    try client.logError("demo", "Operation failed");
}

Custom Logging Callback

fn customLogCallback(entry: *const couchbase.LogEntry) void {
    const level_str = switch (entry.level) {
        .debug => "🐛",
        .info => "ℹ️",
        .warn => "⚠️",
        .err => "❌",
        .fatal => "💀",
    };
    std.debug.print("{s} [{}] {s}: {s}\n", .{ 
        level_str, 
        entry.timestamp, 
        entry.component, 
        entry.message 
    });
}

// Use custom callback
client.setLogCallback(customLogCallback);

Error Context with Logging

// Create detailed error context
var error_context = try client.createErrorContext(
    couchbase.Error.DocumentNotFound,
    "get",
    status_code,
);
defer error_context.deinit();

// Add context information
try error_context.withKey("user:123");
try error_context.withCollection("users", "default");
try error_context.addMetadata("retry_count", "3");
try error_context.addMetadata("timeout_ms", "5000");

// Log with full context
try client.logErrorWithContext("operations", "Failed to retrieve document", &error_context);

Testing

New Test Suite

  • Error Handling Tests: Comprehensive tests for error context creation and management
  • Logging Tests: Tests for all logging levels and configurations
  • Custom Callback Tests: Tests for user-defined logging callbacks
  • Integration Tests: End-to-end tests with client operations

Test Coverage

  • Error Context: 8 test cases covering creation, metadata, and cleanup
  • Logging System: 6 test cases covering all log levels and configurations
  • Client Integration: 3 test cases covering client logging methods
  • Custom Callbacks: 2 test cases covering callback functionality

Performance

Optimizations

  • Efficient Log Level Checking: Minimal overhead for log level filtering
  • Memory Management: Automatic cleanup of error context and log entries
  • Structured Data: Efficient storage and retrieval of error metadata
  • Callback Performance: Fast callback invocation with minimal overhead

Memory Usage

  • Error Context: ~200-500 bytes per context (depending on metadata)
  • Log Entries: ~100-300 bytes per entry (depending on message length)
  • Automatic Cleanup: All allocated memory is automatically freed

Migration Guide

From v0.5.2

  • No Breaking Changes: All existing code continues to work
  • Optional Features: Error handling and logging are opt-in
  • Backward Compatibility: All existing APIs remain unchanged

New Dependencies

  • No External Dependencies: Uses only standard library features
  • libcouchbase Integration: Leverages existing libcouchbase error codes
  • Memory Management: Uses existing allocator patterns

Documentation Updates

New Documentation

  • Error Handling Guide: Comprehensive guide to error context usage
  • Logging Guide: Detailed logging configuration and usage
  • API Reference: Complete API documentation for new types
  • Examples: Working examples for all new features

Updated Documentation

  • README.md: Updated with error handling and logging features
  • CHANGELOG.md: Added v0.5.3 release notes
  • GAP_ANALYSIS.md: Updated to reflect completed error handling features

Bug Fixes

Compilation Issues

  • Format Specifiers: Fixed all format specifier issues in logging
  • Error Type Handling: Proper handling of Zig error types in logging
  • Memory Management: Fixed memory leaks in error context cleanup
  • Type Safety: Improved type safety in logging callbacks

Runtime Issues

  • Error Context Cleanup: Proper cleanup of nested allocations
  • Log Entry Management: Correct memory management for log entries
  • Callback Safety: Safe callback invocation patterns

Future Enhancements

Planned Features

  • Structured Logging: JSON-formatted log output
  • Log Rotation: Automatic log file rotation
  • Metrics Integration: Integration with metrics collection
  • Distributed Tracing: Support for distributed tracing systems

Performance Improvements

  • Async Logging: Asynchronous log processing
  • Log Batching: Batch log processing for high-throughput scenarios
  • Memory Pooling: Object pooling for error contexts and log entries

Conclusion

Version 0.5.3 significantly enhances the Couchbase Zig client with comprehensive error handling and logging capabilities. These features provide the foundation for robust production applications with excellent debugging and monitoring capabilities.

The implementation maintains the client's high performance while adding powerful diagnostic tools that integrate seamlessly with existing code. All features are optional and backward-compatible, ensuring smooth upgrades from previous versions.


Full Changelog: https://github.com/your-repo/couchbase-zig-client/compare/v0.5.2...v0.5.3