0

I need to fetch records from Azure application insights using C#.

I have tried using the below approach, but it requires an app service to be created in Azure and I want to avoid it.

https://learn.microsoft.com/en-us/azure/azure-monitor/app/app-insights-azure-ad-api

I have also followed this answer as well, OP has suggested using https://www.nuget.org/packages/Azure.Monitor.Query but it looks very old, so I would like to know if is this still valid.

Alternative to https://www.nuget.org/packages/Microsoft.Azure.ApplicationInsights/

So I am confused, Could you please help me with the correct approach? My requirement is not to create any extra resources in Azure and wants to fetch from app insights using C#.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
  • Please refer this [thread](https://stackoverflow.com/a/76529407/19648279). – Harshitha Jun 22 '23 at 09:58
  • @Harshitha I don't want to configure app insights. It's already there. I just want to fetch lets app insights using my C# code. so for example it should fetch the result of the query `traces | where cloud_RoleName == "someService"` – Vivek Nuna Jun 22 '23 at 10:12
  • Ok.Yes,AFAIK,the Nuget Package `Azure.Monitor.Query` is still valid.If it is not supported they would have updated the package as deprecated. – Harshitha Jun 22 '23 at 10:16
  • Both the packages work.`Azure.Monitor.Query` can be used if you want to query complex queries.And if you want to go for a basic and simple queries suggest you to use `Microsoft.Azure.ApplicationInsights`. – Harshitha Jun 22 '23 at 10:23

1 Answers1

1

If you already have Application Insights configured, you can query the data as long as you configure a workspace.

For example, once a workspace is configured, a generic method like below can be used to query against a WorkspaceId:

private async Task<IReadOnlyList<T>> QueryAsync<T>(string query, TimeSpan timeSpan)
{
    var response = await _client.QueryWorkspaceAsync<T>(_options.WorkspaceId, query, new QueryTimeRange(timeSpan));

    return response.Value;
}

where _client is:

Azure.Montitor.Query.LogsQueryClient _client;

An example query could be as such:

public async Task<int> GetFailedViewCount()
{
    var query = $"AppEvents" +
        $"| extend Output = tostring(Properties[\"Output\"]) " +
        $"| where Output contains (\"Failed to execute internal view\")" +
        $"| summarize Count=count()";

    var response = await QueryAsync<int>(query, TimeSpan.FromHours(48));

    return response.FirstOrDefault();
}

where we have a CustomEvent (in application insights) which becomes an AppEvent in Workspace, which has been created from a docker container.

James Gould
  • 4,492
  • 2
  • 27
  • 50