如何全局跟踪.net core 2.1中的所有HTTP请求?

时间:2019-07-09 08:22:45

标签: c# .net-core dotnet-httpclient system.diagnostics

我想在dotnet core 2.1应用程序中记录所有HTTP请求。日志记录应包括HTTP标头,正文和主机地址。我需要在不更改现有代码的情况下全局绑定我的日志记录代码。

我尝试了这个示例https://www.azurefromthetrenches.com/capturing-and-tracing-all-http-requests-in-c-and-net/,但是没有HTTP事件传给侦听器。

有没有办法在全球范围内监听dotnet core 2.1上的HTTP事件?

2 个答案:

答案 0 :(得分:4)

This is a good blog post关于Steve Gordon在.Net Core 2.1中的HttpClient登录。

本质上,您需要将System.Net.Http.HttpClient的日志记录级别设置为Trace,以获取有关请求和响应的详细信息。

appsettings.json中必填部分的示例如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "System.Net.Http.HttpClient": "Trace"
    }
  }

这将显示所有HttpClient请求和响应的所有跟踪日志记录。

答案 1 :(得分:1)

您可以在中间件中记录所有http请求信息。看下面的例子

1。创建一个类RequestHandlerMiddleware.cs

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.IO;
using System.Threading.Tasks;

namespace Onsolve.ONE.WebApi.Middlewares
{
    public sealed class RequestHandlerMiddleware
    {
        private readonly RequestDelegate next;
        private readonly ILogger logger;

        public RequestHandlerMiddleware(ILogger<RequestHandlerMiddleware> logger, RequestDelegate next)
        {
            this.next = next;
            this.logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            logger.LogInformation($"Header: {JsonConvert.SerializeObject(context.Request.Headers, Formatting.Indented)}");

            context.Request.EnableBuffering();
            var body = await new StreamReader(context.Request.Body).ReadToEndAsync();
            logger.LogInformation($"Body: {body}");
            context.Request.Body.Position = 0;

            logger.LogInformation($"Host: {context.Request.Host.Host}");
            logger.LogInformation($"Client IP: {context.Connection.RemoteIpAddress}");
            await next(context);
        }

    }
}

2。在RequestHandlerMiddleware的{​​{1}}方法中添加Configure

Startup.cs

或更简单

app.UseMiddleware<RequestHandlerMiddleware>();

参考:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-2.2

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write?view=aspnetcore-2.2