Adventures with App Insights: Tracking Custom Events in an ASP.NET Core Web Application

I wanted to see how to track custom events in Azure Application Insights with an ASP.NET Core Web Application.

A lot of what I wanted to do was found in the article, Application Insights for ASP.NET Core applications, I wanted to streamlined things a bit, specific to my use case.

Let’s get started!

In Azure, you will need to create a Resource Group, and then create an Application Insights resource.

Create a Web Application project in either Visual Studio or VS Code..

I named my Web Application, WebApp1.

Install the NuGet Package Microsoft.ApplicationInsights.AspNetCore to add Application Insights support.

In the Azure Portal, navigate to your Application Insights resource and copy the Instrumentation Key.

Open the appSettings.Development.json file.

Replace the InstrumentationKey value with the Instrumentation Key value for your Application Insights resource.

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "ApplicationInsights": {
    "InstrumentationKey": "YOUR_APPLICATION_INSIGHTS_INSTRUMENTATION_KEY"
  }
}

In the Startup.cs file, in the Configure method, add the line services.AddApplicationInsightsTelemetry().

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddApplicationInsightsTelemetry();
}

This will wire up Application Insights.

Now on to tracking some events in our Web Application!

Update the contents of the ValuesController.cs class, which is created by default in Visual Studio, to the code snippet that follows:

using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace WebApp1.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        readonly TelemetryClient _telemetryClient;

        public ValuesController(
            TelemetryClient telemetryClient)
        {
            _telemetryClient = telemetryClient;
        }

        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            _telemetryClient.TrackEvent(
                "Get");

            return new string[] { "value1", "value2" };
        }

        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            _telemetryClient.TrackEvent(
                "Get",
                new Dictionary<string, string>() { { "id", id.ToString() } });

            return "value";
        }

        [HttpPost]
        public ActionResult<string> Post([FromBody] string value)
        {
            _telemetryClient.TrackEvent(
               "Post",
                new Dictionary<string, string>() { { "value", value } });

            return value;
        }

        [HttpPut("{id}")]
        public ActionResult<string> Put(int id, [FromBody] string value)
        {
            _telemetryClient.TrackEvent(
               "Put",
                new Dictionary<string, string>() { { "id", id.ToString() }, { "value", value } });

            return value;
        }

        [HttpDelete("{id}")]
        public void Delete(int id)
        {
            _telemetryClient.TrackEvent(
                "Delete",
                new Dictionary<string, string>() { { "id", id.ToString() } });
        }
    }
}

Some background on what is going on.

The TelemetryClient is being injected, thanks to our Startup.cs configuration.

In each method we want to track, in Application Insights, the request type and any variables that were passed.

Run the Web App.

In Postman, create requests for the GET, POST, PUT and DELETE against the API methods in our Web Application.

In the Azure Portal, navigate to the Application Insights resource, and click Log Analytics.

Query your custom events by entering customEvents in the prompt and click Run.

You should see a list of your custom events.

Please note, it may take a couple of minutes for the data to actually show up in Azure Application Insights.

Thanks for reading!

Leave a Reply

Your email address will not be published.