Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to link exceptions to requests in Application Insights on Azure?

Tags:

We are using Owin on Azure for a REST service, and have to report to Application Insights directly. We want to log exceptions and requests. Right now we have this:

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);
    }
}

They are registered to our application like so:

static void ConfigureInsights(IAppBuilder app, HttpConfiguration config)
{
    var rtClient = new TelemetryClient();
    app.Use<InsightsReportMiddleware>(rtClient);
    config.Services.Add(typeof (IExceptionLogger), new InsightsExceptionLogger(rtClient));
}

This works, except exceptions and requests are not connected. Both get logged, but when clicking on a failed request it says "No related exceptions were found". Conversely, when opening an exception properties, we can read "Requests affected by this exception: 0". What is the proper way to do that?

like image 528
trethaller Avatar asked May 27 '15 14:05

trethaller


People also ask

How do I log exceptions in application Insights?

Diagnose exceptions using Visual StudioOpen the Application Insights Search telemetry window in Visual Studio. While debugging, select the Application Insights dropdown box. Select an exception report to show its stack trace. To open the relevant code file, select a line reference in the stack trace.

How do I integrate Azure application Insights?

Application Insights is enabled through either Auto-Instrumentation (agent) or by adding the Application Insights SDK to your application code. Many languages are supported and the applications could be on Azure, on-premises, or hosted by another cloud.

What is the difference between application Insights and Azure monitor?

PRO TIP: Please be advised that there is a difference between Azure monitor and application insights. Azure monitor is a service that provides monitoring and diagnostics for resources in Azure, while application insights is a service that provides monitoring and diagnostics for web applications.


1 Answers

Application Insights links exceptions and requests by comparing ExceptionTelemetry.Context.Operation.Id and RequestTelemetry.Id.

I don't have a code sample for OWIN, however the ASP.NET 5 package of the Application Insights SDK has similar middleware components for tracking exceptions and requests. I hope you can use this information to build a solution for OWIN.

We create a RequestTelemetry instance and store it in the request processing environment before invoking the next middleware component which performs actual request processing. In ASP.NET 5, we register RequestTelemetry as a request-scoped service. With OWIN, I'd imagine your middleware component would create it and store it in the environment dictionary.

We also have an ITelemetryInitializer, called OperationIdTelemetryInitializer, that sets the ITelemetry.Context.Operation.Id with the RequestTelemetry.Id extracted from the environment. This initializer needs to be added to the TelemetryConfiguration used to create the TelemetryClient instances in your application. TelemetryConfiguration.Active is used by default.

like image 102
Oleg Sych Avatar answered Sep 20 '22 09:09

Oleg Sych