How to Create Custom Events, Metrics, Traces in Azure Application Insights using C#

2 Comments

In our previous post, we created a Web API app running in Azure with Application Insights enabled. In this post, we will show how to write custom events to App Insights using C#.

We will use the same Web API code we installed in the previous post. Open the project in Visual Studio and install the Microsoft.ApplicationInsights NuGet package:

Click OK:

Now the code. Let’s add an Event, a Metric and a Trace. We will add it to the Get controller method: We will create a TelementryClient object and use TrackEvent, TrackMetric, and TrackTrace:

[sourcecode language=”CSharp”] // Track Event
var telemetryClient = new TelemetryClient();
telemetryClient.InstrumentationKey = "your instrumentation key";

telemetryClient.TrackEvent("This is a test event");
telemetryClient.TrackMetric("Test Metric", 777);
telemetryClient.TrackTrace("Test Trace Message", Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Information);

[/sourcecode]

It should look like:

Now Publish your project so the cloud version has the latest code, then browse out to the API to make a call:

In the Azure portal, in App Insights go to Events to see the new event. Note this may take some time to appear:

And selecting it:

For the custom metric created, go to Metrics:

And for the Trace, we will go to Search:

 

Carl de Souza
Keep learning. Keep building.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.

Subscribe on YouTube →
Carl de Souza Enterprise Architect at Microsoft · AI Technology Expert
See more articles on: Azure

2 Responses to How to Create Custom Events, Metrics, Traces in Azure Application Insights using C#

    • If I run the app locally and it’s connected to App Insights, I’m able to see the data in App Insights just fine

Leave a Reply

Your email address will not be published. Required fields are marked *