I have enabled IIS logging with custom fields for my website.

Previously in MVC, I have used HTTPHandlers and Module to add the above fields to the HTTP Request headers.
web.config:
 <modules runAllManagedModulesForAllRequests="true">
     <!--Handler to process the IIS logs of the site Pagevisit logs-->
    <add name="IISLogger" type="MySite.Website.MvcApplication.Utils.IISLogHandler, MySite.Website.MvcApplication" />
</modules>
IISLogHandler class:
public class IISLogHandler : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }
        private void context_BeginRequest(object sender, EventArgs e)
        {
              var request = (sender as HttpApplication).Request;
              request.Headers["IIID"] = iiid;
              request.Headers["IID"] = !string.IsNullOrEmpty(customerId) ? 
               customerId : iid;
        }
}
My Generated log:

How do i migrate this to ASPNET Core 2.2.0 ?
According to the "Migrating the HTTP handlers and modules code to ASP.NET Core middleware" documentation the following template could help with implementation:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
public class LoggingMiddleware
{
    private readonly RequestDelegate _next;
    public string iid = Guid.NewGuid().ToString();
    public string customerId = string.Empty;
    public LoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task Invoke(HttpContext context)
    {
        
        // Do something with context near the beginning of request processing.
        context.Request.Headers["IIID"] = Guid.NewGuid().ToString();
        context.Request.Headers["IID"] = !string.IsNullOrEmpty(customerId) ? customerId : iid;
        await _next.Invoke(context);
        // Clean up.
    }
}
public static class LoggingMiddlewareExtensions
{
    public static IApplicationBuilder UseLoggingMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<LoggingMiddleware>();
    }
}
public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseLoggingMiddleware();
    }
}
Also, there is related issue opened on github
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With