Code Monkey home page Code Monkey logo

applicationinsights-owinextensions's Introduction

Application Insights OWIN extensions

This library is a set of extensions, that allow you to easily get some features normally not available for OWIN based applications out-of-the-box (but are available when using the classic ASP.NET pipeline).

Features

  • Sets the common Context.Operation.Id property for all telemetries within one request (even asynchronously called dependencies)
  • Pass Context.Operation.Id property between multiple dependencies request chains
  • Creates Request telemetry with proper name, id and execution time
  • Useable with both self-hosted and System.Web hosted OWIN applications

Installation

Required steps

Install Application Insights within the project like you would normally do. You may also want to update related nuget packages to latest versions.

Install the extensions package:

Install-Package ApplicationInsights.OwinExtensions

In your Startup class, add as a first step of the pipeline:

public class Startup
{
	public void Configuration(IAppBuilder app)
	{
		app.UseApplicationInsights();
		
		// rest of the config here...
	}
}

Cleanup the ApplicationInsights.config by removing telemetry initializers and modules with overlapping functionality.

  • Microsoft.ApplicationInsights.Web.OperationCorrelationTelemetryInitializer
  • Microsoft.ApplicationInsights.Web.OperationIdTelemetryInitializer
  • Microsoft.ApplicationInsights.Web.OperationNameTelemetryInitializer

and also the Microsoft.ApplicationInsights.Web.RequestTrackingTelemetryModule

One last thing to do is to configure the Operation Id telemetry initializer. With XML in ApplicationInsights.config:

<TelemetryInitializers>
	<!-- other initializers ... -->
	<Add Type="ApplicationInsights.OwinExtensions.OperationIdTelemetryInitializer, ApplicationInsights.OwinExtensions"/>
</TelemetryInitializers>

or in code:

TelemetryConfiguration.Active
	.TelemetryInitializers.Add(new OperationIdTelemetryInitializer());

Possibly required steps

Note: If you are using Microsoft.Owin.Security.* middlewares, you need to restore the Operation Id context one step after the authentication middleware - otherwise the Operation Id context will be lost. This problem is most probably related to the security middleware taking advantage of the old System.Web pipeline integration and setting the stage markers. The problem will probably surface also with other middlewares using the stage markers.

// ...
app.UseOAuthBearerTokens(OAuthOptions);
// ...

// now restore the Operation Id context from the OWIN environment dictionary
app.RestoreOperationIdContext();

Advanced usage

Selectively tracing requests

You can pass a parameter to the UseApplicationInsights method specifying request filtering callback.

appBuilder.UseApplicationInsights(new RequestTrackingConfiguration
{
    ShouldTrackRequest = ctx => Task.FromResult(ctx.Request.Method != "OPTIONS")
});

Selectively tracing exceptions

You can specify filter to ignore certain exceptions. By default, OperationCancelledException is ignored if client cancelled the request. If you specify your own filter, also include the cancelled request condition.

appBuilder.UseApplicationInsights(new RequestTrackingConfiguration
{
    ShouldTrackException = ctx => async (ctx, e) => 
        await DefaultFilters.ShouldTrackException(ctx, e) && !(e is MyException)
});

Adding custom properties to telemetry

You can also extend the traced telemetry with custom properties. Note: if your custom properties are not related to the request or the response, you can alternatively specify additional TelemetryInitializer in your Application Insights telemetry configuration.

appBuilder.UseApplicationInsights(new RequestTrackingConfiguration
{
    GetAdditionalContextProperties = ctx =>
        Task.FromResult(new[] { new KeyValuePair<string, string>("Content-Type", ctx.Request.ContentType)}
            .AsEnumerable())
});

Modifying TelemetryContext with data from OwinContext

Additionally, you can enrich the telemetry context with information from the OwinContext. You can use this to modify the user context of the Request Telemetry.

appBuilder.UseApplicationInsights(new RequestTrackingConfiguration
{
    ModifyTelemetryContext = (owinContext, telemetryContext) =>
		{
			telemetryContext.User.Id = owinContext.Authentication.User.Identity.Name;
			return Task.CompletedTask;
		}
});

Passing OperationId via header

Let's presume that your system is build of many services communicating by http requests with each other . You probably would like to be able to track how the specific operation propagate through your system's components. To achieve this you should append the operation id to each request with a header. Provided middleware can acquire that id, use it with its own telemetry and then it can be passed to next component. And so on...

This behaviour is turned off by default. Following snippets present how to turn it on.

public class Startup
{
	public void Configuration(IAppBuilder app)
	{
		app.UseApplicationInsights(			
		  new OperationIdContextMiddlewareConfiguration { OperationIdFactory = IdFactory.FromHeader("X-My-Operation-Id") });
		  
		// rest of the config here...
	}
}

Example how to perform http request with appended Context.Operation.Id value:

using (var client = new HttpClient())
{
	var request = new HttpRequestMessage
	{
		Method = HttpMethod.Get,
		RequestUri = new Uri($"http://{serviceHost}:{servicePort}")
	};

	request.Headers.Add("X-My-Operation-Id", OperationContext.Get().OperationId);
	await client.SendAsync(request);
}

The OperationContext is a static class storing current request Context.Operation.Id value.

Changing how ids are generated

By default, new ids are generated as Guids. You can change that by providing delegates in OperationIdContextMiddlewareConfiguration.OperationIdFactory and RequestTrackingConfiguration.RequestIdFactory.

Operation scope and parent operation id

You can create sub-operations and manage the OperationParentId via the OperationContextScope.

using (new OperationContextScope("operationId", "parentOperationId")) 
{
	// telemetries sent here will have specified ids set
}

You should keep the same operation id for all requests, dependencies, etc. that make up a single logical operation you want to track. Change the parent operation id to create a tree of sub-operations.

If you are implementing a middleware, you may want to also save the new values in the OWIN environment dictionary, so that they can be restored via RestoreOperationIdContext. To learn more about parent operation id, see this article.

using (new OperationContextScope("operationId", "parentOperationId")) 
using (new OperationContextStoredInOwinContextScope(owinContext))
{
	// telemetries sent here will have specified ids set
}

Optional steps

You can use ComponentNameTelemetryInitializer to add ComponentName property to your telemetry. It will simplify filtering telemetries connected with specific component of your system.

TelemetryConfiguration.Active
	.TelemetryInitializers.Add(new ComponentNameTelemetryInitializer("MyComponentName"));

How this stuff works

First middleware in the pipeline establishes a new Operation Id context (Guid.NewGuid() by default). This value is stored both in OWIN environment dictionary under the ApplicationInsights.OwinExtensions.OperationIdContext key, and in the CallContext. There is the OperationIdContext class that can be used to access the current value of Operation Id from anywhere within the call context. The telemetry initializer makes use of that and sets appropriate property on the telemetries.

Contributing

If you would like to contribute, please create a PR against the develop branch.

Release notes

0.9.0

  • [FEATURE] - allow modifying telemetry context before sending, see #38

0.8.1

  • [FIX] - fix for dependencies issue introduced by 0.8.0, see #37

0.8.0

  • [FIX] - fix for OperationCancelledException and TaskCancelledException being logged in telemetry

0.7.0

  • [MAINTENANCE] - bumped dependency on Microsoft.ApplicationInsights to >= 2.0

0.6.0

  • [BREAKING] - removed the IdGenerationStrategy - use OperationIdContextMiddlewareConfiguration.OperationIdFactory and RequestTrackingConfiguration.RequestIdFactory
  • [BREAKING] - at least .NET 4.6.1 is required now
  • [FEATURE] - parent operation id can be managed with OperationContextScope
  • [FEATURE] - establishing OperationId and RequestId can be customized and based on current OWIN context

0.5.1

  • [FIX] - #24 temporary fix for operation parent id not set on telemetry

0.5.0

  • [BREAKING] (possibly) - UseApplicationInsights now accepts an instance of RequestTrackingConfiguration instead of separate configuration parameters. Old overload has been deprecated
  • [FEATURE] - IOwinContext is passed to request filter and additional properties extractor delegates
  • [FEATURE] - request filter and additional properties extractor delegates are now async

0.4.1

  • [FIX] Fixed #17 - incorrect logging when exception thrown from downstream OWIN pipeline

0.4.0

  • [FEATURE] It is now possible to add custom properties to the logged request telemetry by providing a delegate in UseApplicationInsights

0.3.0

  • [FEATURE] It is now possible to filter logged request telemetries by providing a delegate in UseApplicationInsights

applicationinsights-owinextensions's People

Contributors

bacobart avatar bogdangrigg avatar damian-krychowski avatar lefoulkrod avatar marcinbudny avatar martinay avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

applicationinsights-owinextensions's Issues

Expose TelemetryClient?

First I'm new to Application Insights so I could be totally off base here.

The problem I'm trying to solve is I'd like to be able to record things like the User Id, Device Id, etc for each request.

I'm presuming/hoping that if you exposed TelemetryClient, or allow it to be passed in to the constructor for the middleware, I could then modify those properties during the pipeline to add those details?

Eg. I've created a static TelemetryClient within my OWIN Service that I then update via an AuthenticationFilter. This is logged via Traces (I'm using Serilog.Sinks.ApplicationInsights so my logging automatically gets traced) but obviously not along with the Requests that your extension is providing.

Paket

Seems like a good library you've made. Unfortunately I can't say the same for the package manager you've chosen. I've been trying to restore packages for over an hour and have given up.

Could not install package 'ApplicationInsights.OwinExtensions 0.6.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5.2'

Hi,

I'm trying to install the NuGet package but getting this error:

Could not install package 'ApplicationInsights.OwinExtensions 0.6.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5.2', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

Is it possible to use these extensions with framework version 4.5.2?

Support for DependencyCollector?

Hello,

thanks for your Extension!
I have a question though: it seems that dependent Downstream calls are not being tracked as Depenedent Calls. My WebApi uses a DLL that in turn makes http-calls to other devices.
From using AI.WCF, I know that these calls can usually be tracked as dependent calls.
How can I achieve this with WebAPI / Owin.Extensions?
I've added the DependentCollector Initializer, but to no avail.

Any idea?

Many thanks!!!
Alexander

Add correlation ID to headers

When integrating with other parts of our systems we would rather just propagate correlation ID through the header instead of using OperationIdContext.Get() in multiple places withon our code. It would be pretty neat if I could toggle on an option to enable the correlation ID header to be added if not found based on the value in OperationIdContext.Get().

Currently I work around this by just adding another middleware:

appBuilder.Use((IOwinContext owinContext, Func<Task> next) =>
{
    if (!owinContext.Request.Headers.ContainsKey(HttpHeaders.CorrelationId))
    {
        owinContext.Request.Headers[HttpHeaders.CorrelationId] = OperationIdContext.Get();
    }

    return next();
});

but I think it would be way more convenient if I could just configure the OperationIdContextMiddlewareConfiguration instance with a property like ShouldWriteHeader = true .

Add paramters from OwinContext?

How would I go about adding custom properties from the owin context?

For example I have a middleware that sets some user information in the OWIN context and I would like to have a initializer/processor add these to all the telemetry.

Assembly Not Signed

Hi,
I find that these assemblies is unsigned. Any specific reasons for the same?

unsignedassembly

Since, i am leveraging this nuget in my build, I am facing compliance issues while using this nuget.

Please release a signed (strong named) version of this nuget asap. Thanks in advance!

ApplicationInsights.OwinExtensions.HttpRequestTrackingMiddleware+<Invoke>d__4.MoveNext

SDK version:
"ApplicationInsights.OwinExtensions" Version="0.6.0"
"Microsoft.ApplicationInsights" Version="2.8.1"
"Microsoft.ApplicationInsights.DependencyCollector" Version="2.8.1"
"Microsoft.ApplicationInsights.PerfCounterCollector" Version="2.8.1"
"Microsoft.ApplicationInsights.Web" Version="2.8.1"
"Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel" Version="2.8.1"
"Microsoft.AspNet.WebApi.Owin" Version="5.2.6"

.NET runtime version (.NET or .NET Core, TargetFramework in the .csproj file):
Microsoft.NET Framework 4.6.1

Hosting Info (IIS/Azure WebApps/etc):
Azure Service Fabric

Describe exactly how to reproduce the error. Include a code sample if applicable.
We are listening to external dependency using Application insights. we are getting errors in OWIN listener package.

we are capturing the external calls. We also get these errors too.

Additional context.

image

ApplicationInsights.config
https://github.com/arunbalajip/Issues/blob/master/ApplicationInsights.config

ParentId is not set

I found out that when I send Error data to ApplicationInsights, the telemetry data misses the ParentId. The result is that the error is not correctly correlated with the root operation. No exception data is provided when looking at a failed request (just "Learn how to track exceptions for failed requests").

Also see http://stackoverflow.com/questions/42858598/exceptions-are-not-shown-in-request-details-but-under-server-exceptions-in-appli

Unfortunately, I have no clue what changes are needed to get the parent Id so that it could be set inside OperationIdTelemetryInitializer

System.Threading.Tasks.TaskCancelledException:

System.Threading.Tasks.TaskCanceledException:
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Web.Http.Controllers.ApiControllerActionInvoker+d__0.MoveNext (System.Web.Http, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Web.Http.Controllers.ActionFilterResult+d__2.MoveNext (System.Web.Http, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Web.Http.Filters.AuthorizationFilterAttribute+d__2.MoveNext (System.Web.Http, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Web.Http.Dispatcher.HttpControllerDispatcher+d__1.MoveNext (System.Web.Http, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Web.Http.HttpServer+d__0.MoveNext (System.Web.Http, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Web.Http.Owin.HttpMessageHandlerAdapter+d__0.MoveNext (System.Web.Http.Owin, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at ApplicationInsights.OwinExtensions.HttpRequestTrackingMiddleware+d__4.MoveNext (ApplicationInsights.OwinExtensions, Version=0.5.1.0, Culture=neutral, PublicKeyToken=null)

This exception appears to be occurring perhaps 1 in every 1000 requests, on the back of a POST ( which is likely immaterial here) .

In relation to a previous similar bug, you suggested a forceful client disconnection.
Is there anyway I can get any more logging around this?

operation_Name Missing From Custom Event Data

When we were using IIS hosting, we were getting the operation_Name (e.g. "GET /version") for free. Now that we've switched to OWIN hosting and this package, that isn't being logged anymore. I don't know if that's a deficiency in this package or a limitation in OWIN hosting. We can certainly add this data ourselves, but I wanted to make sure there wasn't some other way I was missing before going that route.

This extension killed my webapp performance

While doing some load testing I was getting 300 requests / second and when I added this in and used it by doing app.UseApplicationInsights(); it killed the performance down to 50 requests / second.

Any idea what is going on?

I can still enable app insights by just setting the instrumentation key like this :
Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.InstrumentationKey = "mykey";

Conflicting version of Microsoft.Owin

I just installed the latest 0.8.0 version of this package and am getting Microsoft.Owin package version issues.

According to the package details, Microsoft.Owin >= 2.0.2 is supported, however when I add it, I get this issue (we are currently running 3.1.0 for a lot of bad reasons, but I can't upgrade easily)

image

A binding redirect like

			<dependentAssembly>
				<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
				<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="3.1.0.0"/>
			</dependentAssembly>

works, but I don't think it should be necessary?

Is the package being built against the incorrect Microsoft.Owin version (compared to the listed dependencies)?

Support for getContextPropertiesAsync

Hi,
As an improvement, it'd be nice to support getContextPropertiesAsync (adding a new parameter).
This way we'd be able to implement custom tracing that reads in the body of a POST request for example.
The impact should be limited to HttpRequestTrackingMiddleware (TraceRequest, ctor, props, Invoke) as well as AppBuilderExtension (UseApplicationInsights).
Let me know if you need more information.

Under Load we see this exception

System.OperationCanceledException:
at System.Threading.CancellationToken.ThrowOperationCanceledException (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Web.Http.Owin.HttpMessageHandlerAdapter+d__13.MoveNext (System.Web.Http.Owin, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Web.Http.Owin.HttpMessageHandlerAdapter+d__0.MoveNext (System.Web.Http.Owin, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at ApplicationInsights.OwinExtensions.HttpRequestTrackingMiddleware+d__4.MoveNext (ApplicationInsights.OwinExtensions, Version=0.4.1.0, Culture=neutral, PublicKeyToken=null)

Set requestId and parentId to correlate dependencies to requests in the azure portal

Right now the dependencies are shown only under "All items for this operation", but not in the request view itself on azure portal.

The reason for that is the portal correlates dependencies to requests based on the dependencies parentId to the requests requestId.

To fix, simply set requestId and parentId to the context Id in OperationIdTelemetryInitializer.cs.

The code I use in my own TelemetryInitializer is as follows:

    public void Initialize(ITelemetry telemetry)
    {
      var operationId = OperationIdContext.Get();
      if (string.IsNullOrEmpty(operationId)) return;

      telemetry.Context.Operation.ParentId = operationId;

      // Is this a TrackRequest() ?
      if (!(telemetry is RequestTelemetry requestTelemetry)) return;
      requestTelemetry.Id = operationId;
    }

I believe requestId is already being set, but I included it just in case.

Request / Dependency Correlation.

Currently correlation can be achieved between a request and it's dependencies via the OperationalId. However the application insights eco-system encourages correlation using an operational scope as well. Can operational scope be added to help correlate a request with its dependencies e.g.

// Establish an operation context and associated telemetry item:
using (var operation = telemetry.StartOperation<RequestTelemetry>("operationName"))
{
    // Telemetry sent in here will use the same operation ID.
    ...
    telemetry.TrackEvent(...); // or other Track* calls
    ...
    // Set properties of containing telemetry item - for example:
    operation.Telemetry.ResponseCode = "200";

    // Optional: explicitly send telemetry item:
    telemetry.StopOperation(operation);

} // When operation is disposed, telemetry item is sent.

In the long run this maybe more complex then initial thought. If the operation scope is implemented within the Invoke method then a "name" for the operation is required. ASP.net acquires the name via the OperationNameTelemetryInitializer using the HttpContext::CreateRequestNamePrivate which uses request/method/routing data to create the name. The issue here is that at the time invoke is called the HttpMessageHandler has yet to be invoked so the routing data is missing.

Question: No data about failed requests

Hi,

I ask here because I have no clue where else to put this question (other than StackOverflow). Please point me to a better location :-)

I instrumented our ASP.NET Web.Api project with Application Insights. Because we use the OWIN middleware, it did not work until I added your applicationinsights-owinextensions package and followed the instructions in the readme.

Now I see requests/sec and request duration inside Application Insights.

However, there is no data about failed calls sent to Application Insights.

Any hint is welcome.

Thanks for your extension!
Urs

HTTP 500s not being logged

When an exception is thrown, the telemetry for the request is not being sent. I'm expecting the request to be logged as a 500. This is pretty critical.

<Add Type="Microsoft.ApplicationInsights.Web.ExceptionTrackingTelemetryModule, Microsoft.AI.Web"/>

is still enabled in ApplicationInsights.config, but does not appear to work for OWIN. I didn't see any calls to TrackException in this code. Thoughts?

Service Fabric Owin OperationIdContext is null

Seen a couple of issues related to the OperationId being null but they seem to have gone off the grid due to inactivity. I tried using the RestoreOperationIdContext() just before UseWebApi() however the id still remains null. In a nutshell this is what I have:

            app.Use<Middleware1>();
            app.Use<Middleware2>();
            app.UseApplicationInsights();
            config.MapHttpAttributeRoutes();
            app.RestoreOperationIdContext();
            app.UseWebApi(config);

Thanks.

OperationIdContext.Get() returns null

I am trying to link my sql queries to my web requests in application insights. To do this, I added an interceptor and am trying to use OperationIdContext.Get() but it always returns null for some reason. Maybe I cam confused on how it works but I assumed an OperationIdContext is set at the beginning of every request?

Why would this not be populated?

How to set the user context of RequestTelemetry

I do not find a way to set the user context of the RequestTelemetry. I can get the user information out of the Owin context. Adding it to the additional context properties like this works:

        appBuilder.UseApplicationInsights(new RequestTrackingConfiguration
        {
            GetAdditionalContextProperties = owinContext =>
            {
                var additionalProperties = new List<KeyValuePair<string, string>>();

                if (owinContext.Request.User is ClaimsPrincipal claimsPrincipal)
                {
                    var userId = claimsPrincipal.GetUserId().ToString();
                    additionalProperties.Add(new KeyValuePair<string, string>("UserId", userId));
                }

                return Task.FromResult(additionalProperties.AsEnumerable());
            }
        });

Unfortunately, this results in the UserId being part of the custom data. I.e. the User tracking of App Insights will not be populated.

Is there any way to set the built-in user context of the RequestTelemetry object?

When to remove the optional TelemetryInitializers

We are using the owin extension, but we have a question about the optional TelemetryInitializers.
In the documentation page, you mention that these can optionally be removed in most cases.
Can you explain in what cases you cannot remove them? We are using ASP.NET 4.6 with Owin. Can we remove them?

ObjectDisposedException at ApplicationInsights.OwinExtensions.HttpRequestTrackingMiddleware

We are heavily calling CosmosDB, but we do not explicitly dispose anything. We get the exception randomly after an outgoing call which returns 200.

ObjectDisposedException at ApplicationInsights.OwinExtensions.HttpRequestTrackingMiddleware

System.ObjectDisposedException:
at System.Net.HttpListenerResponse.CheckDisposed (System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Net.HttpListenerResponse.set_ContentLength64 (System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at Microsoft.Owin.Host.HttpListener.RequestProcessing.HeadersDictionaryBase.Set (Microsoft.Owin.Host.HttpListener, Version=3.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)
at System.Web.Http.Owin.HttpMessageHandlerAdapter.SendResponseMessageAsync (System.Web.Http.Owin, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)
at System.Web.Http.Owin.HttpMessageHandlerAdapter+d__0.MoveNext (System.Web.Http.Owin, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at Microsoft.CommonSchema.Services.Owin.Internal.IncomingHandler+d__0.MoveNext (Microsoft.CommonSchema.Services.Owin, Version=4.2.0.0, Culture=neutral, PublicKeyToken=872fbc9102191257Microsoft.CommonSchema.Services.Owin, Version=4.2.0.0, Culture=neutral, PublicKeyToken=872fbc9102191257: c:\B\15\CommonSchemaSvcLib_LiveFour\S\private\CommonSchemaSvcLib\Source\Microsoft.CommonSchema.Services.Owin\Internal\IncomingHandler.csMicrosoft.CommonSchema.Services.Owin, Version=4.2.0.0, Culture=neutral, PublicKeyToken=872fbc9102191257: 46)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at Microsoft.Owin.Cors.CorsMiddleware+d__0.MoveNext (Microsoft.Owin.Cors, Version=3.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at ApplicationInsights.OwinExtensions.HttpRequestTrackingMiddleware+d__4.MoveNext (ApplicationInsights.OwinExtensions, Version=0.6.0.0, Culture=neutral, PublicKeyToken=null)

System.OperationCanceledException and System.ObjectDisposedException

Hello!
I'm using OWIN self-hosting in Azure microservices. After I added applicationinsights owinextensions I regularly see these two exceptions.
Stacks traces below

System.OperationCanceledException:
at System.Threading.CancellationToken.ThrowOperationCanceledException (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Web.Http.Owin.HttpMessageHandlerAdapter+d__13.MoveNext (System.Web.Http.Owin, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Web.Http.Owin.HttpMessageHandlerAdapter+d__0.MoveNext (System.Web.Http.Owin, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at ApplicationInsights.OwinExtensions.HttpRequestTrackingMiddleware+d__4.MoveNext (ApplicationInsights.OwinExtensions, Version=0.6.0.0, Culture=neutral, PublicKeyToken=null)

Cannot access a disposed object.
Object name: 'System.Net.HttpListenerResponse'.
System.ObjectDisposedException:
at System.Net.HttpListenerResponse.CheckDisposed (System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Net.HttpListenerResponse.set_ContentLength64 (System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at Microsoft.Owin.Host.HttpListener.RequestProcessing.HeadersDictionaryBase.Set (Microsoft.Owin.Host.HttpListener, Version=3.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)
at System.Web.Http.Owin.HttpMessageHandlerAdapter.SendResponseMessageAsync (System.Web.Http.Owin, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)
at System.Web.Http.Owin.HttpMessageHandlerAdapter+d__0.MoveNext (System.Web.Http.Owin, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)
at ApplicationInsights.OwinExtensions.HttpRequestTrackingMiddleware+d__4.MoveNext (ApplicationInsights.OwinExtensions, Version=0.6.0.0, Culture=neutral, PublicKeyToken=null)

SQL Query details are not available in AppInsights

Not sure whether this really is a concern of your library, but I found no other clue why the SQL statements sent to our Azure SQL server do not show. The dependency details just show the server and the table name.

Everything I found either says to upgrade to .net 4.6 or install Status Monitor - which does not apply for hosting in Azure Web Apps.

Our WebApi runs under .net 4.6 in a Azure Web App with extension ApplicationInsights enabled and connects to a Azure SQL server.

Thanks for your help in advance :-)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.