需要添加两个Nuget包分别是:Microsoft.AspNetCore.MiddlewareAnalysis
和Microsoft.Extensions.DiagnosticAdapter
,前者是分析记录中间件核心代码实现后者是用来接收日志输出的,由于是用的DiagnosticSource方式记录日志,所以需要使用DiagnosticListener对象的SubscribeWithAdapter方法来订阅。
这个适配器是为了方便我们把从DiagnosticSource接收到的日志对象输出到控制台,具体代码实现如下
public class AnalysisDiagnosticAdapter
{
private readonly ILogger<AnalysisDiagnosticAdapter> _logger;
public AnalysisDiagnosticAdapter(ILogger<AnalysisDiagnosticAdapter> logger)
{
_logger = logger;
}
[DiagnosticName("Microsoft.AspNetCore.MiddlewareAnalysis.MiddlewareStarting")]
public void OnMiddlewareStarting(HttpContext httpContext, string name, Guid instance, long timestamp)
{
_logger.LogInformation($"中间件-启动: '{name}'; Request Path: '{httpContext.Request.Path}'");
}
[DiagnosticName("Microsoft.AspNetCore.MiddlewareAnalysis.MiddlewareException")]
public void OnMiddlewareException(Exception exception, HttpContext httpContext, string name, Guid instance, long timestamp, long duration)
{
_logger.LogInformation($"中间件-异常: '{name}'; '{exception.Message}'");
}
[DiagnosticName("Microsoft.AspNetCore.MiddlewareAnalysis.MiddlewareFinished")]
public void OnMiddlewareFinished(HttpContext httpContext, string name, Guid instance, long timestamp, long duration)
{
_logger.LogInformation($"中间件-结束: 耗时[{duration/10000}] '{name}'; Status: '{httpContext.Response.StatusCode}'");
}
}
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMiddlewareAnalysis();
var listener = app.Services.GetRequiredService<DiagnosticListener>();
var observer = ActivatorUtilities.CreateInstance<AnalysisDiagnosticAdapter>(app.Services);
using var disposable = listener.SubscribeWithAdapter(observer);
日志已经成功的输出到我们的控制台了,不过才四个中间件,应该不止这么少的,再在注册中间件分析服务那里添加一句代码
var builder = WebApplication.CreateBuilder(args);
// 新增的下面这句代码
builder.Services.Insert(0, ServiceDescriptor.Transient<IStartupFilter, AnalysisStartupFilter>());
builder.Services.AddMiddlewareAnalysis();
现在再来看看效果,发现变成8个中间件了多了四个
在Release模式编译后,运行发现中间件的执行效率非常高,几乎不占用时间
"异常"记录这里就不放图了,有兴趣的朋友自己去试试。 简单三步就可以知道一个请求到底执行了哪些中间件还是挺方便的。想知道实现原理可以去看看Microsoft.AspNetCore.MiddlewareAnalysis这个库,一共才四个文件看起来不费事。