在 ASP.NET C# Web API 中实现 Serilog 以增强请求和响应的日志记录

介绍

        日志记录是任何 Web 应用程序的关键方面。它有助于调试、性能监控和了解用户交互。在 ASP.NET C# 中,集成 Serilog 作为记录请求和响应(包括传入和传出的数据)的中间件可以显著提高 Web API 的可观察性和故障排除能力。

        在过去的几周里,我一直在编写一些使用 Azure 表存储而不是 SQL 或 Postgres 数据库的不同 Web API,因为表存储非常便宜,而数据库很昂贵,而且我想尝试使用表存储来看看它在实际应用程序中有多么有用。

        在这篇博文中,我将介绍使用 Serilog 在 ASP.NET C# Web API 中创建中间件类以进行全面日志记录的步骤。

设置 Serilog

        首先,您需要将 Serilog 集成到您的 ASP.NET C# 项目中。Serilog 是一个功能强大且易于使用的日志库。

        安装 Serilog 包:通过 NuGet 包管理器,安装Serilog、、Serilog.AspNetCore和Serilog.Sinks.File(或您选择的任何其他接收器)。
配置 Serilog:在您的Program.cs或 中Startup.cs,将 Serilog 配置为日志提供程序:

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .WriteTo.Console()
    .WriteTo.File("logs/myapp.txt", rollingInterval: RollingInterval.Day)
    .CreateLogger();

创建中间件

        ASP.NET Core 中的中间件是组装到应用程序管道中以处理请求和响应的软件。

        创建一个新的中间件类SerilogMiddleware.cs:在您的项目中创建一个新类。

        实现中间件逻辑:此类将拦截所有 HTTP 请求和响应,使我们能够记录必要的信息。

public class SerilogMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task Invoke(HttpContext context)
    {
        // Log the Request
        Log.Information($"Request {context.Request?.Method}: {context.Request?.Path.Value}");

        // Read and log the request body data
        string requestBodyPayload = await ReadRequestBody(context);
        Log.Information($"Request Payload: {requestBodyPayload}");

        // Copy a pointer to the original response body stream
        var originalBodyStream = context.Response.Body;

        using (var responseBody = new MemoryStream())
        {
            // Point the response body to a memory stream
            context.Response.Body = responseBody;

            await _next(context);

            // Read and log the response body data
            context.Response.Body.Seek(0, SeekOrigin.Begin);
            string responseBodyPayload = await new StreamReader(context.Response.Body).ReadToEndAsync();
            context.Response.Body.Seek(0, SeekOrigin.Begin);

            Log.Information($"Response {context.Response?.StatusCode}: {responseBodyPayload}");

            // 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(originalBodyStream);
        }
    }

    private async Task<string> ReadRequestBody(HttpContext context)
    {
        context.Request.EnableBuffering();

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

        return bodyAsText;
    }
}

注册中间件

在该Startup.cs文件中,在方法中注册中间件Configure。 

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ... other configurations ...

    // Register the Serilog middleware
    app.UseMiddleware<SerilogMiddleware>();

    // ... other configurations ...
}

结论

        您已通过在 ASP.NET C# Web API 中实现 Serilog 中间件建立了强大的日志记录机制。这将记录所有请求和响应及其有效负载,让您详细了解 API 的运行情况。此设置对于诊断问题、了解用户行为和确保应用程序平稳运行非常有用。

        请记住,虽然记录必不可少,但谨慎记录内容也至关重要,尤其是在处理敏感数据时。始终遵守有关数据处理和隐私的最佳实践和法律要求。

您可以从这里下载 Serilog:https://serilog.net

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

csdn_aspnet

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值