Serilog记录Web-API方法,在中间件内部添加上下文属性

时间:2020-02-05 13:28:19

标签: asp.net-core asp.net-core-webapi serilog asp.net-core-middleware

我一直在努力用serilog记录响应主体有效负载数据,并从中间件记录日志。 我正在开发 WEB API Core 应用程序,并在端点上添加了 swagger ,我的目标是将每个端点调用记录到 .json serilog 的文件(请求和响应数据)。

对于 GET 请求,应记录响应的主体(作为属性添加到serilog上下文中),对于POST请求,应记录请求和响应的主体。 我已经创建了中间件,并设法从请求和响应流中正确检索数据,并将其作为字符串获取,但只有“ RequestBody” 被正确记录。

调试时,我可以看到读取请求/响应主体工作正常。

以下是程序-> Main方法的代码摘录:

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration)
    .Enrich.FromLogContext()
    .CreateLogger();

和中间件中的代码:

public async Task Invoke(HttpContext context)
{
    // Read and log request body data
    string requestBodyPayload = await ReadRequestBody(context.Request);

    LogContext.PushProperty("RequestBody", requestBodyPayload);

    // Read and log response body data
    var originalBodyStream = context.Response.Body;
    using (var responseBody = new MemoryStream())
    {
        context.Response.Body = responseBody;
        await _next(context);
        string responseBodyPayload = await ReadResponseBody(context.Response);

        if (!context.Request.Path.ToString().EndsWith("swagger.json") && !context.Request.Path.ToString().EndsWith("index.html"))
        {
            LogContext.PushProperty("ResponseBody", responseBodyPayload);
        }

        await responseBody.CopyToAsync(originalBodyStream);
    }
}

private async Task<string> ReadRequestBody(HttpRequest request)
{
    HttpRequestRewindExtensions.EnableBuffering(request);

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

    return $"{requestBody}";
}

private async Task<string> ReadResponseBody(HttpResponse response)
{
    response.Body.Seek(0, SeekOrigin.Begin);
    string responseBody = await new StreamReader(response.Body).ReadToEndAsync();
    response.Body.Seek(0, SeekOrigin.Begin);

    return $"{responseBody}";
}

正如我提到的,“ RequestBody” 已正确记录到文件中,但“ ResponseBody” 却没有任何记录(甚至没有添加为属性) 感谢任何帮助。

3 个答案:

答案 0 :(得分:7)

从多个帖子中收集信息并根据我的需求对其进行自定义之后,我找到了一种将请求和响应正文数据记录为serilog日志结构的属性的方法。

我没有找到一种只在一个地方记录请求和响应正文的方法(在中间件的Invoke方法中),但是我找到了一种解决方法。由于请求处理管道的性质,这是我必须要做的:

Startup.cs中的代码:

app.UseMiddleware<RequestResponseLoggingMiddleware>();
app.UseSerilogRequestLogging(opts => opts.EnrichDiagnosticContext = LogHelper.EnrichFromRequest);
  • 我已经使用LogHelper类来丰富请求属性,就像Andrew Locks post中所述。

  • 当请求处理命中中间件时,在中间件的Invoke方法中,我读取仅请求正文数据,并将此值设置为我拥有的静态字符串属性已添加到LogHelper类中。这样,我已将请求正文数据读取并存储为字符串,并且可以在调用LogHelper.EnrichFromRequest方法时将其添加为richer

  • 在读取请求正文数据之后,我正在将指针复制到原始响应正文流

  • await _next(context);接下来被调用,context.Response被填充,请求处理从中间件的Invoke方法退出,并转到LogHelper.EnrichFromRequest

    < / li>
  • 目前LogHelper.EnrichFromRequest正在执行,现在读取响应正文数据,并将其设置为richer,以及先前存储的请求正文数据和一些其他属性

  • 处理返回到中间件Invoke方法(在await _next(context);之后),然后将新内存流(包含响应)的内容复制到原始流中,

以下是上面LogHelper.csRequestResponseLoggingMiddleware.cs类中描述的代码:

LogHelper.cs:

public static class LogHelper
{
    public static string RequestPayload = "";

    public static async void EnrichFromRequest(IDiagnosticContext diagnosticContext, HttpContext httpContext)
    {
        var request = httpContext.Request;

        diagnosticContext.Set("RequestBody", RequestPayload);

        string responseBodyPayload = await ReadResponseBody(httpContext.Response);
        diagnosticContext.Set("ResponseBody", responseBodyPayload);

        // Set all the common properties available for every request
        diagnosticContext.Set("Host", request.Host);
        diagnosticContext.Set("Protocol", request.Protocol);
        diagnosticContext.Set("Scheme", request.Scheme);

        // Only set it if available. You're not sending sensitive data in a querystring right?!
        if (request.QueryString.HasValue)
        {
            diagnosticContext.Set("QueryString", request.QueryString.Value);
        }

        // Set the content-type of the Response at this point
        diagnosticContext.Set("ContentType", httpContext.Response.ContentType);

        // Retrieve the IEndpointFeature selected for the request
        var endpoint = httpContext.GetEndpoint();
        if (endpoint is object) // endpoint != null
        {
            diagnosticContext.Set("EndpointName", endpoint.DisplayName);
        }
    }

    private static async Task<string> ReadResponseBody(HttpResponse response)
    {
        response.Body.Seek(0, SeekOrigin.Begin);
        string responseBody = await new StreamReader(response.Body).ReadToEndAsync();
        response.Body.Seek(0, SeekOrigin.Begin);

        return $"{responseBody}";
    }
}

RequestResponseLoggingMiddleware.cs:

public class RequestResponseLoggingMiddleware
{
    private readonly RequestDelegate _next;

    public RequestResponseLoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        // Read and log request body data
        string requestBodyPayload = await ReadRequestBody(context.Request);
        LogHelper.RequestPayload = requestBodyPayload;

        // Read and log response body data
        // Copy a pointer to the original response body stream
        var originalResponseBodyStream = context.Response.Body;

        // Create a new memory stream...
        using (var responseBody = new MemoryStream())
        {
            // ...and use that for the temporary response body
            context.Response.Body = responseBody;

            // Continue down the Middleware pipeline, eventually returning to this class
            await _next(context);

            // Copy the contents of the new memory stream (which contains the response) to the original stream, which is then returned to the client.
            await responseBody.CopyToAsync(originalResponseBodyStream);
        }
    }

    private async Task<string> ReadRequestBody(HttpRequest request)
    {
        HttpRequestRewindExtensions.EnableBuffering(request);

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

        return $"{requestBody}";
    }
}

答案 1 :(得分:0)

接受的答案不是线程安全的。

<块引用>

LogHelper.RequestPayload = requestBodyPayload;

当有多个并发请求时,这种分配会导致意外的日志结果。
我没有使用静态变量,而是直接将请求正文推送到 Serilog 的 LogContext 属性中。

答案 2 :(得分:0)

如果登录到文件,我们可以添加以下代码以及来自 .net core 5.0 中 @Vladimir 的答案。

在 Program.cs 中添加 UseSerilog

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        })
        .UseSerilog((hostingContext, services, loggerConfig) =>
         loggerConfig.ReadFrom.Configuration(hostingContext.Configuration)
             .WriteTo.Logger(lc => lc.Filter.ByIncludingOnly(Matching.FromSource("Serilog.AspNetCore.RequestLoggingMiddleware")).WriteTo.File(path: "Logs/WebHookLog_.log",
                 outputTemplate: "{Timestamp:o}-{RequestBody}-{ResponseBody}-{Host}-{ContentType}-{EndpointName} {NewLine}", rollingInterval: RollingInterval.Day))
        );

要在 appsettings.json 中添加的字段:

  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Default": "Information",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          "path": "Logs/applog_.log",
          "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
          "rollingInterval": "Day",
          "retainedFileCountLimit": 7
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName" ],
    "Properties": {
      "Application": "AspNetCoreSerilogDemo"
    }
  },