Add Metrics to Application Insights

November 29, 2023

In this earlier post I covered adding App Insights to a web application using Open Telemetry.

Here, we’ll cover adding metrics to that same app.

Before we do, let’s quickly cover why you might add metrics to an application.


Metrics are an interesting facet of a monitoring system: they essentially allow you to count things. That doesn’t sound very useful, unless you care how many things there are. Say you have sales orders, you might want to store the number of orders and the value. This allows you to record those figures: it also allows you to alert on that value (for example, if the average order value is too low).


We’ll continue from the previous post, and add the metrics:

var metricsProvider = Sdk.CreateMeterProviderBuilder()

You can now inject this into your web app:

private const string meterName = "NoSearch.Search";
private static readonly Meter meter = new(meterName);

In the method itself:

var counter = meter.CreateCounter<int>("SearchCounter");

This will now start to emit the metrics. You can view these by selecting the metric from the list of custom metrics:

Metrics - Select Custom

Then you can view the count:

Metrics - View

That’s pretty cool, but now we have that, we can use it to alert on. In my case, I’m firing this when a search happens, so maybe I want to see when the number of searches goes over or under a given amount, or I just want to know when the number of searches changes from the norm.

Start by setting an alert rule, and defining a condition:

Alerts - Condition

The new custom metric is now available in the list of signals:

Alerts - New Metric

Now you’ve defined that signal, you can create a static or dynamic rule. Let’s start with static:

Alerts - Condition

This allows you to define that, when your metric goes above or below a certain threshold, you want to do something. For example, if I wanted to know when the number of searches exceeded 12, I might use this.

However, a more appropriate rule for me would be dynamic:

Alerts - Dynamic Condition

What I actually want is to know when the number of searches changes. I’ve written about Azure Monitor Alerts before. However, once you’ve configured the condition, you then need to define an action - this allows you to define a notification (i.e. tell someone that something has happened) and an action (i.e. do something about it automatically):

Alerts - Action


Profile picture

A blog about one man's journey through code… and some pictures of the Peak District

© Paul Michaels 2024