新问网站设计,江苏省住建厅官方网,网站修改用什么工具,网站开发培训达内前言上次#xff0c;我们介绍了如何《在业务层实现响应缓存》。今天#xff0c;我们同样使用IPipelineBehavior#xff0c;介绍如何在业务层实现记录请求日志#xff0c;用于跟踪每个请求执行的耗时。Demo创建ASP.NET Core Web API项目#xff0c;引用Nuget包#xff1a;… 前言上次我们介绍了如何《在业务层实现响应缓存》。今天我们同样使用IPipelineBehavior介绍如何在业务层实现记录请求日志用于跟踪每个请求执行的耗时。Demo创建ASP.NET Core Web API项目引用Nuget包MediatR
MediatR.Extensions.Microsoft.DependencyInjection1.实现IPipelineBehavior创建LoggingBehavior用于实现记录请求日志逻辑:public class LoggingBehaviorTRequest, TResponse : IPipelineBehaviorTRequest, TResponse
{private readonly ILoggerLoggingBehaviorTRequest, TResponse _logger;public LoggingBehavior(ILoggerLoggingBehaviorTRequest, TResponse logger){_logger logger;}public async TaskTResponse Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegateTResponse next){var stopwatch new Stopwatch();stopwatch.Start();var response await next();stopwatch.Stop();_logger.LogInformation(${typeof(TRequest).Name}耗时:{stopwatch.ElapsedMilliseconds});return response;}
}2.注册IPipelineBehavior修改Startup.csservices.AddMediatR(Assembly.GetExecutingAssembly());
services.AddTransient(typeof(IPipelineBehavior,), typeof(LoggingBehaviour,))3.测试修改WeatherForecastController使用Mediatorpublic class WeatherForecastController : ControllerBase
{private readonly IMediator _mediator;public WeatherForecastController(IMediator mediator){this._mediator mediator;}[HttpGet]public async TaskIEnumerableWeatherForecast Get(){return await this._mediator.Send(new GetWeatherForecastQuery()); }
}public class GetWeatherForecastQuery : IRequestIEnumerableWeatherForecast
{
}internal class GetWeatherForecastQueryHandler : IRequestHandlerGetWeatherForecastQuery, IEnumerableWeatherForecast
{public async TaskIEnumerableWeatherForecast Handle(GetWeatherForecastQuery request, CancellationToken cancellationToken){await Task.Delay(1000);var rng new Random();return Enumerable.Range(1, 1).Select(index new WeatherForecast{ TemperatureC rng.Next(-20, 55),Summary Summaries[rng.Next(Summaries.Length)]}).ToArray();}
}为了体现效果代码里故意加了等待时间。运行程序在控制台界面可以看到输出的日志。结论可以看到在业务层实现记录请求日志功能十分的简单如果你觉得这篇文章对你有所启发请关注我的个人公众号”My IO“