NetCore的全局日志记录

Http进来的数据和出去的数据都记录在log中

 

public class HttpLoggingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<HttpLoggingMiddleware> _logger;

    public HttpLoggingMiddleware(RequestDelegate next, ILogger<HttpLoggingMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // 记录请求信息
        var request = context.Request;
        var requestLog = new StringBuilder();
        requestLog.AppendLine("HTTP Request Information:");
        requestLog.AppendLine($"Method: {request.Method}");
        requestLog.AppendLine($"Path: {request.Path}");
        requestLog.AppendLine("Headers:");
        foreach (var header in request.Headers)
        {
            requestLog.AppendLine($"{header.Key}: {header.Value}");
        }
        requestLog.AppendLine("Query Parameters:");
        foreach (var param in request.Query)
        {
            requestLog.AppendLine($"{param.Key}: {param.Value}");
        }

        if (request.ContentLength > 0 || request.Headers.ContainsKey("Transfer-Encoding"))
        {
            request.EnableBuffering();
            using (var reader = new StreamReader(request.Body, Encoding.UTF8, true, 1024, true))
            {
                var body = await reader.ReadToEndAsync();
                requestLog.AppendLine($"Body: {body}");
                request.Body.Position = 0;
            }
        }

        _logger.LogInformation(requestLog.ToString());

        // 记录响应信息
        var originalBodyStream = context.Response.Body;
        var responseBody = new MemoryStream(); // 替换响应流
        context.Response.Body = responseBody;

        try
        {
            await _next(context); // 调用下一个中间件

            // 重置并读取响应流
            context.Response.Body.Seek(0, SeekOrigin.Begin);
            var responseText = await new StreamReader(context.Response.Body).ReadToEndAsync();
            context.Response.Body.Seek(0, SeekOrigin.Begin);

            if (context.Response.ContentType != null && context.Response.ContentType.Contains("application/json"))
            {
                var responseLog = new StringBuilder();
                responseLog.AppendLine("HTTP Response Information:");
                responseLog.AppendLine($"Status Code: {context.Response.StatusCode}");
                responseLog.AppendLine("Headers:");
                foreach (var header in context.Response.Headers)
                {
                    responseLog.AppendLine($"{header.Key}: {header.Value}");
                }
                responseLog.AppendLine($"Body: {responseText}");

                _logger.LogInformation(responseLog.ToString());
            }

            await responseBody.CopyToAsync(originalBodyStream); // 将响应内容写回原始流
        }
        finally
        {
            // 在 finally 块中确保流被正确释放
            responseBody.Dispose();
            context.Response.Body = originalBodyStream; // 恢复原始响应流
        }
    }
}

 

 

app.UseMiddleware<HttpLoggingMiddleware>();

 

posted @ 2024-07-02 19:56  ProZkb  阅读(22)  评论(0编辑  收藏  举报