当前位置: 首页 > news >正文

在 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

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

http://www.lryc.cn/news/497529.html

相关文章:

  • 2024年顶级小型语言模型前15名
  • 精通 Python 网络安全(一)
  • 【python自动化二】pytest集成allure生成测试报告
  • 网络版本的通讯录青春版(protobuf)
  • 开源模型应用落地-安全合规篇-用户输入价值观判断(三)
  • 神经网络入门实战:(十四)pytorch 官网内置的 CIFAR10 数据集,及其网络模型
  • 【Rust在WASM中实现pdf文件的生成】
  • 在MySQL中执行sum case when报错:SUM does not exist
  • 【openssl】相关指令
  • 实例分割详解
  • D87【python 接口自动化学习】- pytest基础用法
  • 浅谈MySQL路由
  • matlab中disp,fprintf,sprintf,display,dlmwrite输出函数之间的区别
  • 30.100ASK_T113-PRO 用QT编写视频播放器(一)
  • Linux-GPIO应用编程
  • opencvocr识别手机摄像头拍摄的指定区域文字,文字符合规则就语音报警
  • 微服务即时通讯系统(5)用户管理子服务,网关子服务
  • postgreSQL安装后启动有The application server could not be contacted问题
  • 架构05-架构安全性
  • 虚幻引擎---材质篇
  • NPM镜像详解
  • 从智能合约到去中心化AI:Web3的技术蓝图
  • STM32进阶 定时器3 通用定时器 案例1:LED呼吸灯——PWM脉冲
  • 开源即时通讯与闭源即时通讯该怎么选择,其优势是什么?
  • 930[water]
  • 2024论文翻译 | Multi-Review Fusion-in-Context
  • (78)MPSK基带调制通信系统瑞利平坦衰落信道传输性能的MATLAB仿真
  • 【机器学习】机器学习的基本分类-监督学习-决策树-CART(Classification and Regression Tree)
  • 【金猿CIO展】复旦大学附属中山医院计算机网络中心副主任张俊钦:推进数据安全风险评估,防范化解数据安全风险,筑牢医疗数据安全防线...
  • 工业机器视觉-基于深度学习的水表表盘读数识别