在业务层实现记录请求日志
生活随笔
收集整理的這篇文章主要介紹了
在业务层实现记录请求日志
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
前言
上次,我們介紹了如何《在業(yè)務(wù)層實(shí)現(xiàn)響應(yīng)緩存》。
今天,我們同樣使用IPipelineBehavior,介紹如何在業(yè)務(wù)層實(shí)現(xiàn)記錄請(qǐng)求日志,用于跟蹤每個(gè)請(qǐng)求執(zhí)行的耗時(shí)。
Demo
創(chuàng)建ASP.NET Core Web API項(xiàng)目,引用Nuget包:
MediatR MediatR.Extensions.Microsoft.DependencyInjection1.實(shí)現(xiàn)IPipelineBehavior
創(chuàng)建LoggingBehavior,用于實(shí)現(xiàn)記錄請(qǐng)求日志邏輯:
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}耗時(shí):{stopwatch.ElapsedMilliseconds}");return?response;} }2.注冊(cè)IPipelineBehavior
修改Startup.cs:
services.AddMediatR(Assembly.GetExecutingAssembly()); services.AddTransient(typeof(IPipelineBehavior<,>),?typeof(LoggingBehaviour<,>))3.測(cè)試
修改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();} }為了體現(xiàn)效果,代碼里故意加了等待時(shí)間。
運(yùn)行程序,在控制臺(tái)界面可以看到輸出的日志。
結(jié)論
可以看到,在業(yè)務(wù)層實(shí)現(xiàn)記錄請(qǐng)求日志功能,十分的簡(jiǎn)單!
如果你覺(jué)得這篇文章對(duì)你有所啟發(fā),請(qǐng)關(guān)注我的個(gè)人公眾號(hào)”My IO“
總結(jié)
以上是生活随笔為你收集整理的在业务层实现记录请求日志的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: C# GTS四轴运动控制器实例(固高科技
- 下一篇: github开源推荐:SuperSock