我们在 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”。这样做的正确方法是什么?