我们在Azure上使用Owin进行REST服务,并且必须直接向Application Insights报告.我们要记录例外和请求.现在我们有这个:
using AppFunc = Func<IDictionary<string,object>,Task>; public class InsightsReportMiddleware { readonly AppFunc next; readonly TelemetryClient telemetryClient; public InsightsReportMiddleware(AppFunc next,TelemetryClient telemetryClient) { if (next == null) { throw new ArgumentNullException("next"); } this.telemetryClient = telemetryClient; this.next = next; } public async Task Invoke(IDictionary<string,object> environment) { var sw = new Stopwatch(); sw.Start(); await next(environment); sw.Stop(); var ctx = new OwinContext(environment); var rt = new RequestTelemetry( name: ctx.Request.Path.ToString(),timestamp: DateTimeOffset.Now,duration: sw.Elapsed,responseCode: ctx.Response.StatusCode.ToString(),success: 200 == ctx.Response.StatusCode ); rt.Url = ctx.Request.Uri; rt.HttpMethod = ctx.Request.Method; telemetryClient.TrackRequest(rt); } } public class InsightsExceptionLogger : ExceptionLogger { readonly TelemetryClient telemetryClient; public InsightsExceptionLogger(TelemetryClient telemetryClient) { this.telemetryClient = telemetryClient; } public override Task LogAsync(ExceptionLoggerContext context,System.Threading.CancellationToken cancellationToken) { telemetryClient.TrackException(context.Exception); return Task.FromResult<object>(null); } public override void Log(ExceptionLoggerContext context) { telemetryClient.TrackException(context.Exception); } }
他们在我们的应用程序中注册:
static void ConfigureInsights(IAppBuilder app,HttpConfiguration config) { var rtClient = new TelemetryClient(); app.Use<InsightsReportMiddleware>(rtClient); config.Services.Add(typeof (IExceptionLogger),new InsightsExceptionLogger(rtClient)); }
除了异常和请求没有连接外,这是有效的.两者都被记录,但是当点击失败的请求时,它说“没有发现相关的异常”.相反,当打开异常属性时,我们可以看到“受此异常影响的请求:0”.
这样做的正确方法是什么?
解决方法
Application Insights通过比较ExceptionTelemetry.Context.Operation.Id和RequestTelemetry.Id来链接异常和请求.
我没有OWIN的代码示例,但是Application Insights SDK的ASP.NET 5 package具有类似的中间件组件,用于跟踪异常和请求.我希望您可以使用此信息为OWIN构建解决方案.
在调用执行实际请求处理的下一个中间件组件之前,我们创建一个RequestTelemetry实例并将其存储在请求处理环境中.在ASP.NET 5中,我们将RequestTelemetry注册为请求范围的服务.使用OWIN,我可以想象您的中间件组件将创建它并将其存储在环境字典中.
我们还有一个名为OperationIdTelemetryInitializer的ITelemetryInitializer,它将ITelemetry.Context.Operation.Id与从环境中提取的RequestTelemetry.Id进行设置.此初始化器需要添加到用于在应用程序中创建TelemetryClient实例的遥测配置. TelemetryConfiguration.Active默认使用.