Serilog 日志记录 web-api 方法,在中间件中添加上下文属性

Vla*_*mir 8 serilog asp.net-core asp.net-core-middleware asp.net-core-webapi

我一直在努力使用 serilog 记录响应正文有效负载数据,从中间件记录。我工作的WEB API核心应用,与招摇添加到终点,我的目标是为每一个终点呼叫记录到一个以.json与文件serilog(请求和响应数据)。

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

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

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

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration)
    .Enrich.FromLogContext()
    .CreateLogger();
Run Code Online (Sandbox Code Playgroud)

和中间件中的代码:

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}";
}
Run Code Online (Sandbox Code Playgroud)

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

Vla*_*mir 12

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

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

中的代码Startup.cs

app.UseMiddleware<RequestResponseLoggingMiddleware>();
app.UseSerilogRequestLogging(opts => opts.EnrichDiagnosticContext = LogHelper.EnrichFromRequest);
Run Code Online (Sandbox Code Playgroud)
  • 我已经使用LogHelper类来丰富请求属性,正如Andrew Locks 帖子中所述

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

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

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

  • 此时LogHelper.EnrichFromRequest正在执行,现在读取响应体数据,并将其设置为丰富器,以及之前存储的请求体数据和一些附加属性

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

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

日志助手.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}";
    }
}
Run Code Online (Sandbox Code Playgroud)

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}";
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你好,什么是 GetEndpoint() ?它似乎在 Core 3.1 中不可用(使用 IHttpContextAccessor 时也不可用)。 (2认同)
  • @Yovav 嗨。GetEndpoint() 是 HttpContext 对象的扩展方法。它来自NuGet包Microsoft.AspNetCore.Http.Extensions 2.2.0 (2认同)

小智 8

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

LogHelper.RequestPayload = requestBodyPayload;

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