ASP.NET Core on request before started middleware

413 Views Asked by At

I have an asp.net core application and I need to add elastic logging, I decided to use Serilog for it, but I need to add a Correlation id into logs messages, I can't do it within only HTTP correlation id header because I have service bus handlers that also need to have correlation id. So I did it with default asp request middleware, but still have logs without it

request finished/started logs aren't have correlation id

request finished/started logs aren't have correlation id

here is my serilog setup

hostBuilder.UseSerilog(
            (_, _, loggerConfiguration) =>
            {
                loggerConfiguration
                    .Enrich.FromLogContext()
                    .WriteTo.Console()
                    .WriteTo.Elasticsearch(ConfigureElasticSink(configuration, environment))
                    .ReadFrom.Configuration(configuration);
            });

and request middleware

public class CorrelationIdMiddleware
{
    private readonly RequestDelegate _next;

    public CorrelationIdMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context, ICorrelationIdService correlationIdService)
    {
        context.Request.Headers.TryGetValue(Constants.CORRELATION_ID_HEADER_NAME, out var correlationId);
        correlationIdService.Set(correlationId);
        context.Request.Headers.TryAdd(Constants.CORRELATION_ID_HEADER_NAME, correlationIdService.CorrelationId);
        LogContext.PushProperty(Constants.CORRELATION_ID, correlationIdService.CorrelationId);

        await _next(context);
    }
}

UDP

My startup file

using IM360.Logger;
using InMarket360EmailServiceWebApi.WebUI;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddLoggerServices();
builder.Services.AddWebUIServices();

builder.Host.UseExternalLogging();

var app = builder.Build();

app.UseExternalLogging(); //middleware being added in this extension method

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseMigrationsEndPoint();
}
else
{
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseRouting();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

app.MapFallbackToFile("index.html");

app.Run();

public partial class Program { }

Logger extenstions file

        public static IServiceCollection AddLoggerServices(this IServiceCollection serviceCollection)
        {
            serviceCollection.AddScoped<ICorrelationIdService, CorrelationIdService>();
            serviceCollection.AddHeaderPropagation(opt => opt.Headers.Add(Constants.CORRELATION_ID_HEADER_NAME));

            return serviceCollection;
        }

        public static WebApplication UseExternalLogging(this WebApplication webApplication)
        {
            webApplication.UseMiddleware<CorrelationIdMiddleware>();
            webApplication.UseHeaderPropagation();

            return webApplication;
        }

Have any ideas?

0

There are 0 best solutions below