网站界面结构,平面设计公司简介怎么写,sns社交网站注册,白山网络推广介绍 日志记录是任何 Web 应用程序的关键方面。它有助于调试、性能监控和了解用户交互。在 ASP.NET C# 中#xff0c;集成 Serilog 作为记录请求和响应#xff08;包括传入和传出的数据#xff09;的中间件可以显著提高 Web API 的可观察性和故障排除能力。 在过去的几周里集成 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 Taskstring 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.UseMiddlewareSerilogMiddleware(); // ... other configurations ... }
结论 您已通过在 ASP.NET C# Web API 中实现 Serilog 中间件建立了强大的日志记录机制。这将记录所有请求和响应及其有效负载让您详细了解 API 的运行情况。此设置对于诊断问题、了解用户行为和确保应用程序平稳运行非常有用。 请记住虽然记录必不可少但谨慎记录内容也至关重要尤其是在处理敏感数据时。始终遵守有关数据处理和隐私的最佳实践和法律要求。
您可以从这里下载 Seriloghttps://serilog.net 如果您喜欢此文章请收藏、点赞、评论谢谢祝您快乐每一天。