前言
上次,我们介绍了如何《在业务层实现响应缓存》。
今天,我们同样使用IPipelineBehavior,介绍如何在业务层实现记录请求日志,用于跟踪每个请求执行的耗时。
Demo
创建ASP.NET Core Web API项目,引用Nuget包:
MediatR
MediatR.Extensions.Microsoft.DependencyInjection
1.实现IPipelineBehavior
创建LoggingBehavior
,用于实现记录请求日志逻辑:
public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{private readonly ILogger<LoggingBehavior<TRequest, TResponse>> _logger;public LoggingBehavior(ILogger<LoggingBehavior<TRequest, TResponse>> logger){_logger = logger;}public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> 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.cs:
services.AddMediatR(Assembly.GetExecutingAssembly());
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(LoggingBehaviour<,>))
3.测试
修改WeatherForecastController,使用Mediator:
public class WeatherForecastController : ControllerBase
{private readonly IMediator _mediator;public WeatherForecastController(IMediator mediator){this._mediator = mediator;}[HttpGet]public async Task<IEnumerable<WeatherForecast>> Get(){return await this._mediator.Send(new GetWeatherForecastQuery()); }
}public class GetWeatherForecastQuery : IRequest<IEnumerable<WeatherForecast>>
{
}internal class GetWeatherForecastQueryHandler : IRequestHandler<GetWeatherForecastQuery, IEnumerable<WeatherForecast>>
{public async Task<IEnumerable<WeatherForecast>> 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“