如何用NLog在asp.net-core中记录所有请求的正文和详细标头?

2026-03-30 13:231阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计381个文字,预计阅读时间需要2分钟。

如何用NLog在asp.net-core中记录所有请求的正文和详细标头?

我正在使用ASP.NET Core 2.1 WebAPI。能否使用NLog的配置记录当前请求的正文和?请参考以下XML配置:

xml

我正在使用ASP .Net Core 2.1 WebAPI.是否可以使用NLog的配置记录当前请求正文和标题?

如何用NLog在asp.net-core中记录所有请求的正文和详细标头?

<?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="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> 您可以为此实现自定义中间件:

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); } }

在Startup.cs中注册它配置:

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

并更新Program.cs以使用NLog,例如:

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();

本文共计381个文字,预计阅读时间需要2分钟。

如何用NLog在asp.net-core中记录所有请求的正文和详细标头?

我正在使用ASP.NET Core 2.1 WebAPI。能否使用NLog的配置记录当前请求的正文和?请参考以下XML配置:

xml

我正在使用ASP .Net Core 2.1 WebAPI.是否可以使用NLog的配置记录当前请求正文和标题?

如何用NLog在asp.net-core中记录所有请求的正文和详细标头?

<?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="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> 您可以为此实现自定义中间件:

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); } }

在Startup.cs中注册它配置:

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

并更新Program.cs以使用NLog,例如:

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();