
Azure Monitor is the central place for collecting logs and metrics in Azure. Application Insights works on top of Azure Monitor and is designed for supporting custom applications on their monitoring needs. If you have a custom app (= non-Azure service, an exotic piece of software running in a VM for example) you can monitor it via Application Insights. It has multiple technical ways of ingesting custom data. The recommended way is to use a NuGet package, but if you need to interact with Application Insights with a language that is not very fluent with NuGet packages (I am looking at you, PowerShell) there is also a way to send metrics using the REST API.
So, here is a sample how you can ingest metrics using the REST API in PowerShell. A few notes on the following PowerShell snippet:
- You typically get the metric value(s) from somewhere else, how you do it is up to you and the original source system producing the metrics
- You can aggregate multiple postBodyItems in a single POST operation to reduce networking overhead
- AIInstrumentationKey is the instrumentation key that can be found on your Application Insights overview page in Azure portal
- metricNamespace and metricName are your custom values that you need to invent, they will show up in metrics once data has been ingested
- Optional dimensions are categorization for the metrics. Metric data can be filtered based on them. An example of a dimension could be application instance name or customer name.
try {
$AIInstrumentationKey = 'YourKeyHere'
$metricNamespace = 'YourNamespace'
$date = Get-Date -Format o
$metricName = 'YourMetricName'
$metricValue = 1.23
$Dimension1Value = 'YourDimension1'
$Dimension2Value = 'YourDimension2'
$postBodyItem = @"
{
"name": "Microsoft.ApplicationInsights.instrumentation_key.Metric",
"time": "$date",
"iKey": "$AIInstrumentationKey",
"tags": {
"ai.cloud.roleInstance": ".",
"ai.internal.nodeName": ".",
"ai.internal.sdkVersion": "."
},
"data": {
"baseType": "MetricData",
"baseData": {
"ver": 2 ,
"metrics": [{
"name": "$metricName",
"ns": "$metricNamespace",
"kind": "Aggregation",
"value": $metricValue,
"count": 1
}],
"properties": {
"Dimension1": "$Dimension1Value",
"Dimension2": "$Dimension2Value"
}
}
}
}
"@
Write-Host ''
Write-Host -NoNewline 'Sending metrics... '
$result = Invoke-WebRequest -Uri 'https://dc.services.visualstudio.com/v2/track' -ContentType 'application/json' -Method POST -Body $postBodyItem
$resultStats = $result.Content | ConvertFrom-Json
Write-Host "sent $($resultStats.itemsReceived)/$($resultStats.itemsAccepted) metric values."
} catch {
Write-Host $_.Exception.Message
}
Author: Aali Alikoski
More stories about Azure
