I have been using ApplicationInsights for a couple of months now. While it is great for MVC and Web applications in general, I have some WebAPI service applications that I'd like to track the usage for.
For example, I have different RESTful APIs in my application and I'd like to see how many calls are made every day (or over a period of time) to compare usage.
The usage tab in ApplicationInsights seems to be tailor made for HTML Web Applications.
Is there a way to utilize it for services?
If I got your question correctly, you want to determine usage of each API based on users. You already have request data available for every API but it cannot be filtered based on users since we aren't tracking users with every telemetry event.
If you want to filter telemetry data (requests, exceptions etc.) based on users or any property, you would need it to be available in the properties of the telemetry event so that you can directly filter it and generate charts in the metrics explorer. To do this you can create a TelemetryInitializer.
Telemetry initializers allow you to add global properties along with all your telemetry data which means it will be executed for all telemetry events that are sent from your app. Here's an example for tracking UserID along with every telemetry event. I'm assuming that the User.Identity will be set for you since you are using Windows Authentication. This will also work for any other authentication (Azure AD, certificate based authentication etc) too as long as the IPrinicipal is set in the Http Request.
public class UserTelemetryIntitializer : ITelemetryInitializer
{
public void Initialize(Microsoft.ApplicationInsights.Channel.ITelemetry telemetry)
{
var context = HttpContext.Current;
if (context == null)
return;
// If user has authenticated, add a property UserID to telemetry which will have
// * domain\\username for Windows Authentication
// * [email protected] for Azure AD Authentication
if (context.User.Identity.IsAuthenticated)
telemetry.Context.Properties["UserID"] = context.User.Identity.Name;
else
telemetry.Context.Properties["UserID"] = "Null";
}
}
Don't forget to load your telemetry initializer, using ApplicationInsights.config:
<ApplicationInsights>
<TelemetryInitializers>
<!-- Fully qualified type name, assembly name: -->
<Add Type="MvcWebApp.Telemetry.UserTelemetryIntitializer, MvcWebApp"/>
...
</TelemetryInitializers>
</ApplicationInsights>
Alternatively, you could also load the initializer using code instead. In your global.asax.cs or WebApiConfig.cs:
protected void Application_Start()
{
TelemetryConfiguration.Active.TelemetryInitializers
.Add(new UserTelemetryIntitializer());
}
You can read more about Telemetry Initializers here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With