Search code examples
c#azureazure-functionsazure-application-insightskql

Query Azure Application Insights CustomEvents in Azure function in C#.Net


I need to query CustomEvents under application insights in an azure function.

I was able to read CustomEvents using below package: Microsoft.Azure.ApplicationInsights.Query

Here is the code:

string applicationId = "xxxx-xxxx-xxxx";
string key = "xxxxxxxxxxx";

// Create client
var credentials = new ApiKeyClientCredentials(key);
var applicationInsightsClient = new ApplicationInsightsDataClient(credentials);

// Query Application Insights
var query = "customEvents" +
    " | where timestamp > ago(840h)" +
    " | take 3";
var response = await applicationInsightsClient.Query.ExecuteWithHttpMessagesAsync(applicationId, query);

The library 'Microsoft.Azure.ApplicationInsights.Query is however deprecated and suggestion is to use Azure.Monitor.Query

Below is the code that Microsoft documentation has as an example to query logs using Azure.Monitor.Query :

Azure.Response<Azure.Monitor.Query.Models.LogsQueryResult> response = 
    await logsQueryClient.QueryWorkspaceAsync(
        "<workspaceId>",
        "customEvents ",
        new QueryTimeRange(TimeSpan.FromMinutes(300)));

Since this library queries using workspace id, I linked my application insights instance to a log analytics workspace instance. However the function fails with a BadArgumentError "Failed to resolve table or column expression named 'customEvents'"

Is there a way we can query CustomEvents using the package Azure.Monitor.Query?

Any help is appreciated.

Thanks


Solution

  • Yes, it works.
    Below is a tested code.

    Once you link your Application Insights to Azure Monitor workspace, you can query your AI tables from that WS, without the need to use app().
    The thing is that the tables` names are different, e.g., traces becomes AppTraces.

    In the same manner, customEvents becomes AppEvents.

    Well, it turns out it is even documented, under Migrate to workspace-based Application Insights resources

    Legacy table name New table name Description
    availabilityResults AppAvailabilityResults Summary data from availability tests.
    browserTimings AppBrowserTimings Data about client performance, such as the time taken to process the incoming data.
    dependencies AppDependencies Calls from the application to other components (including external components) recorded via TrackDependency() – for example, calls to REST API, database or a file system.
    customEvents AppEvents Custom events created by your application.
    customMetrics AppMetrics Custom metrics created by your application.
    pageViews AppPageViews Data about each website view with browser information.
    performanceCounters AppPerformanceCounters Performance measurements from the compute resources supporting the application, for example, Windows performance counters.
    requests AppRequests Requests received by your application. For example, a separate request record is logged for each HTTP request that your web app receives.
    exceptions AppExceptions Exceptions thrown by the application runtime, captures both server side and client-side (browsers) exceptions.
    traces AppTraces Detailed logs (traces) emitted through application code/logging frameworks recorded via TrackTrace().
    using Azure;
    using Azure.Identity;
    using Azure.Monitor.Query;
    using Azure.Monitor.Query.Models;
    
    string workspaceId = "...";
    
    var client = new LogsQueryClient(new DefaultAzureCredential());
    
    try
    {
        Response<LogsQueryResult> response = await client.QueryWorkspaceAsync(
            workspaceId,
            "AppEvents | count",
            QueryTimeRange.All);
    
        LogsTable table = response.Value.Table;
    
        foreach (var row in table.Rows)
        {
            Console.WriteLine(row);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }