This post was originally published on Marcel de Vries' blog at How to Fix Application insights Live Metrics stream on Azure Mobile Apps.

In preparation for Tech Days 2016, I was working with my colleagues on the Techdays app and for this we also have a backend system. This system is running for some time now and we want to have better insights into the usage of the website and the mobile app.

One of the latest additions to application insights is the capability of Live Metrics, where you can see the current traffic coming into your website or API.

For this you can simply add a NuGet package, which is currently in pre-release, but works great.

Once you install the package and run the website, you will see the Live Stream tile light up in the Azure portal and when you click it you will see a couple of live graphs showing actual traffic on the site or API

Of course we wanted to host our backend very simply on Azure Web apps and for this specific purpose on Azure Mobile Services, Since that is what we use as the mobile backend of the application. But apparently there are some subtle differences that prevent AppInsights to work properly if it comes to Live Metrics.

When running the web API on a local machine with app insights enabled, we could see a nice set of graphs as shown here below:

clip_image002

But when I deploy this to the Azure Mobile services, this results in a page that only shows the dependency calls, bet never any incoming requests and also no request duration. You only see a first request and after this the incoming requests are a flat liner.

clip_image001

After some inquiries at the app insights team, I got the information that since Azure Mobile Services is using OWIN, because the app insights HTTP modules are not loaded since that is not allowed and finally because performance counters are not exposed to the web application, these metrics will not show. After going back and forth on this, I got information that it would be possible to at least get the info for the requests on the screen, by adding a small piece of middleware, that can track the request instead of the standard HttpModule that is normally instantiated, but not allowed in a Mobile app.

So the only thing I needed to do is create a middleware component like the following:

public class ApplicationInsightsMobileAppRequestHandler : OwinMiddleware
{
   private readonly TelemetryClient telemetryClient;
   public ApplicationInsightsMobileAppRequestHandler(OwinMiddleware next) : base(next)
   {
    try
    {
      // The call initializes TelemetryConfiguration that will create and Intialize modules
      TelemetryConfiguration configuration = TelemetryConfiguration.Active;
      telemetryClient = new TelemetryClient(configuration);
    }
    catch (Exception exc)
    {
      Trace.WriteLine("Error initializing Handler");
      Trace.WriteLine(exc.Message);
    }
}

public override async Task Invoke(IOwinContext context)
{
  var operation = telemetryClient.StartOperation<RequestTelemetry>(context.Request.Path.Value);
  try
  {
    var requestTelemetry = operation.Telemetry;
    await this.Next.Invoke(context);
    requestTelemetry.HttpMethod = context.Request.Method;
    requestTelemetry.Url = context.Request.Uri;
    requestTelemetry.ResponseCode = context.Response.StatusCode.ToString();
    requestTelemetry.Success = context.Response.StatusCode >= 200 && context.Response.StatusCode < 300; 
  }
  catch (Exception exc)
  {
    var telemetry = new ExceptionTelemetry(exc);
    telemetry.HandledAt = ExceptionHandledAt.Unhandled;
    telemetryClient.TrackException(telemetry);
  }
  finally
  {
    telemetryClient.StopOperation(operation);
  }
 }
}

And an extension method to register the middleware in the request pipeline at startup in the Startup class:

public static class AppBuilderExtensions
{
  public static IAppBuilder UseMobileAppRequestHandler(this IAppBuilder app)
  {
     return app.Use<ApplicationInsightsMobileAppRequestHandler>();
  }
}

In the application startup class, ensure that you register this handler as the first as follows:

public static void ConfigureMobileApp(IAppBuilder app)
{
  HttpConfiguration config = new HttpConfiguration();
  app.UseMobileAppRequestHandler();
  app.UseWebApi(config);
  ConfigureSwagger(config);
}

And that is it!

When you now deploy tot the azure mobile app, you will see the live metrics as we expect. We still don’t have the memory consumption and CPU usage stats, but this now at least shows all incoming requests in real time

Hope this helps!

Marcel