Skip to content

BipulRaman/CorrelationId

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

11 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

CorrelationId Libraries

A collection of zero-boilerplate correlation ID tracking libraries for .NET applications with automatic integration and configurable additional headers for comprehensive distributed tracing.

.NET NuGet NuGet

πŸ“¦ Packages

Package Description NuGet README
CorrelationId.AspNetCore For ASP.NET Core applications NuGet πŸ“– Documentation
CorrelationId.AzureFunctions For Azure Functions NuGet πŸ“– Documentation

πŸš€ Features

Common Features

  • πŸš€ Zero Boilerplate: No wrapper methods needed - correlation ID available everywhere automatically
  • πŸ”„ Automatic Flow: Correlation ID flows seamlessly through all async operations via AsyncLocal<T>
  • πŸ“¨ Automatic Header Tracking: Tracks X-Correlation-Id and configurable additional headers
  • 🎯 Auto-Generation: Generates new correlation ID if header is missing
  • πŸ“ Automatic Logging: Adds all captured headers to log entries
  • πŸ” Structured Logging: Adds all headers as custom properties for searchable metadata
  • 🌐 HTTP Client Integration: Automatically propagates all headers to outgoing HTTP requests
  • ⚑ Thread-Safe: Uses AsyncLocal<T> for thread-safe header storage
  • πŸŽ›οΈ Configurable Headers: Support for additional custom headers like X-Event-Id, X-User-Id, etc.

ASP.NET Core Specific

  • Middleware Integration: Seamless integration with ASP.NET Core pipeline
  • Named HTTP Clients: Support for multiple configured HTTP clients with correlation
  • Response Headers: Optionally add correlation headers to responses

Azure Functions Specific

  • Multi-Trigger Support: HTTP, Queue, Service Bus, Event Hub, Timer, and Blob triggers
  • Message-Based Correlation: Extracts correlation IDs from queue messages and events
  • Base Class Support: Provides base classes for different trigger types
  • Activity Integration: Works with distributed tracing and Application Insights

πŸ“‹ Quick Start

ASP.NET Core

dotnet add package CorrelationId.AspNetCore
// Program.cs
builder.Services.AddCorrelationId();

app.UseCorrelationId();

// That's it! Correlation ID now available everywhere automatically

Azure Functions

dotnet add package CorrelationId.AzureFunctions
// Program.cs
var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices(services =>
    {
        services.AddCorrelationId(options =>
        {
            options.AdditionalHeaders.AddRange(new[]
            {
                "X-Event-Id",
                "X-User-Id",
                "X-Tenant-Id"
            });
        });
    })
    .Build();

πŸ”§ Usage Examples

Accessing Correlation ID Anywhere

public class MyService
{
    private readonly ICorrelationIdService _correlationService;
    private readonly ILogger<MyService> _logger;

    public MyService(ICorrelationIdService correlationService, ILogger<MyService> logger)
    {
        _correlationService = correlationService;
        _logger = logger;
    }

    public async Task DoSomethingAsync()
    {
        // Get correlation ID anywhere in your application
        var correlationId = _correlationService.CorrelationId;
        
        // Get additional headers
        var userId = _correlationService.GetHeader("X-User-Id");
        var eventId = _correlationService.GetHeader("X-Event-Id");
        
        // All headers automatically included in logs
        _logger.LogInformation("Processing request for user {UserId}", userId);
        
        // Correlation automatically flows to async operations
        await SomeOtherMethodAsync();
    }
}

HTTP Client Integration

// All HTTP clients automatically get correlation headers
public class ApiService
{
    private readonly HttpClient _httpClient;

    public ApiService(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<string> CallExternalApiAsync()
    {
        // Correlation ID and additional headers automatically added
        var response = await _httpClient.GetAsync("https://api.example.com/data");
        return await response.Content.ReadAsStringAsync();
    }
}

πŸ“š Documentation

πŸ› οΈ Configuration Options

Both libraries support extensive configuration:

services.AddCorrelationId(options =>
{
    // Configure additional headers to track
    options.AdditionalHeaders.AddRange(new[]
    {
        "X-Event-Id",
        "X-User-Id", 
        "X-Tenant-Id",
        "X-Request-Source",
        "X-API-Version"
    });
    
    // Add headers to response (ASP.NET Core only)
    options.AddAdditionalHeadersToResponse = true;
    
    // Custom correlation ID header name
    options.CorrelationIdHeaderName = "X-Custom-Correlation-Id";
    
    // Configure HTTP client integration
    options.EnableHttpClientIntegration = true;
});

πŸ—οΈ Architecture

How It Works

  1. Incoming Request: Middleware/Function intercepts incoming requests
  2. Header Extraction: Extracts correlation ID and configured additional headers
  3. Context Storage: Stores headers in AsyncLocal<T> for thread-safe access
  4. Automatic Logging: All log entries include captured headers
  5. HTTP Client Integration: Outgoing requests automatically include headers
  6. Response Headers: Optionally adds headers to response for client tracking

Thread Safety

Both libraries use AsyncLocal<T> to ensure correlation context flows correctly through:

  • Async/await operations
  • Task continuations
  • Thread pool operations
  • Background services

πŸ” Troubleshooting

Common Issues

  1. Headers not flowing: Ensure middleware is registered before other middleware
  2. HTTP client not including headers: Verify HTTP client integration is enabled
  3. Headers missing in logs: Check that structured logging is configured

Logging Integration

Headers are automatically added to:

  • Message Prefix: [CorrelationId: abc123] [X-User-Id: user456] Your log message
  • Structured Properties: Available as searchable metadata in log aggregation systems

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

About

Code repository for CorrelationId NuGet Package.

Resources

License

Stars

Watchers

Forks

Packages

No packages published