Easily Trace Requests Using a Correlation Id

Listen to this Post

Correlation Id is a unique identifier assigned to each request, simplifying the tracing process in distributed systems. It allows tracking requests across multiple services with ease.

You Should Know:

  1. Generating Correlation Id in Middleware (C .NET Example)
    // Add Correlation Id Middleware in ASP.NET Core 
    public class CorrelationIdMiddleware 
    { 
    private readonly RequestDelegate _next; 
    private const string CorrelationIdHeader = "X-Correlation-ID"; </li>
    </ol>
    
    public CorrelationIdMiddleware(RequestDelegate next) 
    { 
    _next = next; 
    }
    
    public async Task Invoke(HttpContext context) 
    { 
    var correlationId = Guid.NewGuid().ToString(); 
    if (!context.Request.Headers.TryGetValue(CorrelationIdHeader, out _)) 
    { 
    context.Request.Headers.Add(CorrelationIdHeader, correlationId); 
    }
    
    context.Response.Headers.Add(CorrelationIdHeader, correlationId); 
    await _next(context); 
    } 
    }
    
    // Register in Startup.cs 
    app.UseMiddleware<CorrelationIdMiddleware>(); 
    

    2. Passing Correlation Id in HTTP Headers

    When calling other services, include the Correlation Id in headers:

    using var httpClient = new HttpClient(); 
    httpClient.DefaultRequestHeaders.Add("X-Correlation-ID", correlationId); 
    

    3. Logging Correlation Id (Serilog Example)

    Log.Information("Request processed. CorrelationId: {CorrelationId}", correlationId); 
    
    1. Linux Command to Trace HTTP Requests (curl with Correlation Id)
      curl -H "X-Correlation-ID: $(uuidgen)" https://api.example.com/endpoint 
      

    2. Extracting Correlation Id from Logs (grep command)

      grep "CorrelationId" /var/log/application.log 
      

    3. Windows PowerShell: Generate and Track Correlation Id

      $correlationId = [bash]::NewGuid().ToString() 
      Invoke-WebRequest -Uri "https://api.example.com" -Headers @{"X-Correlation-ID"=$correlationId} 
      

    What Undercode Say:

    Correlation Ids are essential for debugging distributed systems. By implementing them in middleware, logging, and HTTP calls, you ensure traceability across microservices. Use Linux commands like curl, grep, and PowerShell for testing and log analysis.

    Expected Output:

    A well-structured log with Correlation Ids for easy debugging.

    Source Code: https://www.nikolatech.net/codes/correlation-id-example

    References:

    Reported By: Nikola Knez – Hackers Feeds
    Extra Hub: Undercode MoN
    Basic Verification: Pass ✅

    Join Our Cyber World:

    💬 Whatsapp | 💬 TelegramFeatured Image