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.
Why
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).
How
We’ll continue from the previous post, and add the metrics:
var metricsProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("*")
.AddAzureMonitorMetricExporter()
.Build();
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");
counter.Add(1);
This will now start to emit the metrics. You can view these by selecting the metric from the list of custom metrics:
Then you can view the count:
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:
The new custom metric is now available in the list of signals:
Now you’ve defined that signal, you can create a static or dynamic rule. Let’s start with static:
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:
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):
References
https://learn.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview
https://pmichaels.net/add-app-insights-open-telemetry-client/