We recently encountered a situation where we needed an Azure Function to run regularly, ensuring it performed its tasks successfully. While we aimed to make the function as reliable as possible, we also wanted to incorporate it into our monitoring system. I figured it couldn’t be too difficult since we’re already using some scripts to query data in Azure or Entra through the REST API.
Create the KQL Query
Having a look at the function in Azure, we can quickly see that results are logged in an Application Insights workspace (if enabled under Monitoring → Application Insights). And from the Application Insights Workspace we can easily run queries using KQL.
So first, let’s have a look at the KQL query we need to run to get the results. Specifically, we want to know the number of successful and failed runs of the function over the last 24 hours. We don’t need error details, just the numbers for monitoring and alerting purposes.
So we can open the App Insights Workspace in the Azure Portal, navigate to Monitoring → Logs. On the left-hand side we can already see the available Tables and after a quick search we see that the runs are in the requests
table. And as we just need the number of successful and failed runs, we can use the following query:
requests
| summarize
success_count = countif(success == true),
failed_count = countif(success == false)
Which returns the following result:

As you may guess right now, our function is running every 30 Minutes, leading to 48 runs during the last 24 Hours.
Create the App Registration & add RBAC Permissions
So, now that we know how to query the App Insights Workspace, the next step is to perform this query from the script.
First thing we need to do is to authenticate, and for that, we’re using an App Registration in Entra ID with a Client Secret. Head over to the Microsoft Learn site for more details.
Once you have created your App-Registration, you need to grant the App the required permissions to read the Logs from the App Insights Workspace. So head over to the App Insights Workspace, open the IAM Blade, hit Add → Add role assignment and grant your App Registration the RBAC Role «Log Analytics Reader».
Create the Script
Now that the prerequisites are complete, we can move on to creating the script. We’re using PowerShell with straightforward commands like Invoke-RestMethod
to send the requests.
First things first, we need the following information to connect:
$TenantID = ""
$ClientID = ""
$ClientSecret = ""
$WorkspaceID = ""
The Workspace ID is hidden in your App Insights Workspace under Configure → API Access and marked as the Application ID.
So now we can see if we’re able to get a token from the Microsoft Login endpoint. The Login flow is pretty straightforward and the same as for other Azure Resources, but you need to use https://api.loganalytics.io/
as the resource URI. It took me a while to find the correct URI, as Microsoft’s documentation is somewhat limited on this topic.
We’ll send a POST request to the login endpoint and retrieve the Access Token.
$requestBody = @{
resource = "https://api.loganalytics.io/"
client_id = $ClientID
client_secret = $ClientSecret
grant_type = "client_credentials"
scope = "openid"
}
$auth = Invoke-RestMethod -Method post
-Uri "https://login.microsoftonline.com/$($TenantID)/oauth2/token" `
-Body $requestBody
$Token = $auth.access_token
If everything works fine, we get a Token Type, Expiration Data and of course the Access Token from the Endpoint.
With this Token, we can now fire the request to the App Insights Workspace. But first, we need to assemble our request body. It looks like this: we’ll use the query we tried before and include the timespan parameter to limit the data to the last 24 hours.
$query = "
requests
| summarize
success_count = countif(success == true),
failed_count = countif(success == false)"
$body = @{
query = $query # send the query
timespan = "PT24H" # filter last 24 hours
} | ConvertTo-Json
As a result, we get a JSON-String we can use to send to the App Insights Workspace.
So let’s go. Create the header to authenticate on the Endpoint and send the Post request including the Authorization Header and the Body we have just created.
$authorizationHeader = @{
Authorization = "Bearer $($Token)"
}
$requestBody = @{
Method = "Post"
Uri = "https://api.applicationinsights.io/v1/apps/$($WorkspaceID)/query"
Headers = $authorizationHeader
ContentType = "Application/Json"
Body = $Body
}
$response = Invoke-RestMethod @requestBody
If everything is working fine we get the response from the Endpoint in the $response
variable as you may have expected.
Now we just need to extract the data from the response, and after a quick search we see that it’s hidden in an Array beneath tables → rows. So we can grab the data as follows:
$SuccessfulResult = $response.tables.rows[0]
$FailedResult = $response.tables.rows[1]
From that we can generate the structure our monitoring need to read the data and do its job.
So there’s no magic, but as Microsoft’s docs are pretty slim in some parts, it still took some time to put everything together.
I have added the full script at the end of the Blog-Post.
Takeaways
Of course, this is just the basics without any error handling and I strongly encourage you to add error handling and check if you got the access token, if you got a response from the App Insights Endpoint and if you are able to parse the data.
Also, querying and App Insights Workspace is very similar to querying a Log Analytics Workspace as but have pretty mutch the same functionality and can run KQL queries on tables. But you will need to use another Resource URI (api.loganalytics.azure.com
) when getting the access token and, of course, you’ll need to send your POST-Request to a different endpoint: https://api.loganalytics.azure.com/v1/workspaces/DEMO_WORKSPACE/query
Full Script
$TenantID = ""
$ClientID = ""
$ClientSecret = ""
$WorkspaceID = ""
$requestBody = @{
resource = "https://api.loganalytics.io/"
client_id = $ClientID
client_secret = $ClientSecret
grant_type = "client_credentials"
scope = "openid"
}
$auth = Invoke-RestMethod `
-Method post `
-Uri "https://login.microsoftonline.com/$($TenantID)/oauth2/token" `
-Body $requestBody
$Token = $auth.access_token
$query = "
requests
| summarize
success_count = countif(success == true),
failed_count = countif(success == false)"
$body = @{
query = $query # send the query
timespan = "PT24H" # filter last 24 hours
} | ConvertTo-Json
$authorizationHeader = @{
Authorization = "Bearer $($Token)"
}
$requestBody = @{
Method = "Post"
Uri = "https://api.applicationinsights.io/v1/apps/$($WorkspaceID)/query"
Headers = $authorizationHeader
ContentType = "Application/Json"
Body = $Body
}
$response = Invoke-RestMethod @requestBody
$SuccessfulResult = $response.tables.rows[0]
$FailedResult = $response.tables.rows[1]
Schreiben Sie einen Kommentar