Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging request body and request headers with NLog

I am using ASP .Net Core 2.1 WebAPI. Is it possible to log the current request body and headers with the configurations of the NLog?

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true">
  <extensions>
    <add prefix="custom" assembly="Pepper" />
  </extensions>
  <variable name="log-header" 
            value="Time: [${date}]${newline}
            Operation: ${aspnet-request-method} ${aspnet-request-url:IncludeHost=true:IncludePort=true:IncludeQueryString=true}${newline}
            Headers:${aspnet-request-headers}${newline}
            Body:${aspnet-request-body}"/>
  <targets>
    <target name="exceptionFile" xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
      <target xsi:type="File" 
              encoding="utf-8" 
              fileName="exception_log.txt" 
              archiveAboveSize="10000000" 
              archiveNumbering="Sequence" 
              maxArchiveFiles="10" 
              layout="${log-header}${newline}${message}${newline}${newline}" />
    </target>
  </targets>
  <rules>
    <logger name="*" minlevel="Error" writeTo="exceptionFile" />
  </rules>
</nlog>
like image 660
stefan.stt Avatar asked Jul 30 '18 11:07

stefan.stt


People also ask

How do I start logging with NLog?

Create a Console Application project in Visual Studio. Install NLog and its dependencies. Create and configure the NLog logger. Integrate the logger into the C# Console Application.

What is NLog in API?

NLog is a flexible and free logging platform for various . NET platforms, including . NET standard. NLog makes it easy to write to several targets. (database, file, console) and change the logging configuration on-the-fly.

Does NLog work on Linux?

Save this question.


2 Answers

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();
like image 101
Alex Riabov Avatar answered Nov 24 '22 03:11

Alex Riabov


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 :)

like image 34
cdev Avatar answered Nov 24 '22 05:11

cdev