Logging request body and request headers with NLog

You can implement custom middleware for this:

public class RequestLoggingMiddleware
{
    private readonly RequestDelegate next;
    private readonly ILogger logger;

    public RequestLoggingMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
    {
        this.next = next;
        logger = loggerFactory.CreateLogger<RequestLoggingMiddleware>();
    }

    public async Task Invoke(HttpContext context)
    {
        context.Request.EnableRewind();

        var buffer = new byte[Convert.ToInt32(context.Request.ContentLength)];
        await context.Request.Body.ReadAsync(buffer, 0, buffer.Length);
        var requestBody = Encoding.UTF8.GetString(buffer);
        context.Request.Body.Seek(0, SeekOrigin.Begin);

        var builder = new StringBuilder(Environment.NewLine);
        foreach (var header in context.Request.Headers)
        {
            builder.AppendLine($"{header.Key}:{header.Value}");
        }

        builder.AppendLine($"Request body:{requestBody}");

        logger.LogInformation(builder.ToString());

        await next(context);
    }
}

Register it in Startup.cs Configure:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMiddleware<RequestLoggingMiddleware>();
}

And update Program.cs to use NLog, e.g.:

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
        })
        .UseNLog()  // NLog: setup NLog for Dependency injection
        .Build();

NLog just released feature for log request body.

<layout type="SimpleLayout" text="${newline}Request body: ${aspnet-request-posted-body} " />

You can find feature in

  • https://www.nuget.org/packages/NLog.Web.AspNetCore/4.8.1

  • https://www.nuget.org/packages/NLog.Web/4.8.1

And the usage

  • https://github.com/NLog/NLog/wiki/AspNet-Request-posted-body-layout-renderer

Thank You Julian and NLog Team :)