How to query Application Insights with C#

Application Insights is a great tool for monitoring solutions deployed to Azure.

A user-friendly interface for Application Insights can be found in Azure Portal, and often it’s what we need. However, occasionally, we might want to automate some process that requires access to logs, and we want to query Application Insights from .NET code.

I needed it a few times, and could never easily find a code sample in Google, so I publish my blog post to have such code snippet easily available.

Prerequisites

The code requires installing the Microsoft.Azure.ApplicationInsights.Query package in your project.
You also need to generate a secret key to authenticate to Application Insights API.

Querying Application Insights via API from C#

public async Task GetMostRecentFailedRequests() { // You can generate key in Azure Portal, in Application Insights' "API Access" pane string applicationId = "c22a7f19-b6...[censored]"; string key = "24io8jb...[censored]"; // Create client var credentials = new ApiKeyClientCredentials(key); var applicationInsightsClient = new ApplicationInsightsDataClient(credentials); // Query Application Insights var query = $"requests" + $" | where timestamp > ago(24h)" + $" | where success == false" + $" | order by timestamp desc" + $" | project timestamp, url, resultCode" + $" | take 3"; var response = await applicationInsightsClient.Query.ExecuteWithHttpMessagesAsync(applicationId, query); // Parse result if (response.Response.IsSuccessStatusCode) { foreach (var row in response.Body.Results) { Console.WriteLine($"[{row["timestamp"]:s}][{row["resultCode"]}] Failed request to: {row["url"]}"); } } }
Code language: C# (cs)

// example output of the above function in console window [2021-10-03T11:54:16][404] Failed request to: http://generatordiety.pl/apple-touch-icon.png [2021-10-03T11:05:32][404] Failed request to: http://generatordiety.pl/.env [2021-10-03T11:05:31][404] Failed request to: http://generatordiety.pl/.env
Code language: Access log (accesslog)

Bonus: how to convert DateTimeOffset to a date understood by Kusto

I found DateTimeOffset parameter to be quite often useful in queries. Here is a snippet for this specific type’s conversion that will nicely preserve time zone information:

DateTimeOffset lastMidnight = DateTimeOffset.UtcNow.Date; string query = $"(...) | where timestamp > todatetime(\"{lastMidnight:O}\")"; // The "O" or "o" standard format specifier represents a custom date and time format string using a pattern // that preserves time zone information and emits a result string that complies with ISO 8601.
Code language: C# (cs)

And that’s all here, it should be a good place to start.

Leave a Comment