Application Insights (AI) is the application performance management (APM) and logging platform for Microsoft Azure. They provide a client instrumentation library for several popular platforms/languages– but there isn’t any official module for PowerShell. In this post I share some new functions that demonstrate how to log telemetry data to AI from PowerShell.
Design Approach
Most of the other examples online for logging AI telemetry data within PowerShell will have you have download the Application Insights instrumentation library for .NET, import the library, construct all the objects, and call the Track() methods.
The problem with this approach is that it relies on you downloading and packaging the .NET library with your PowerShell functions or module. This is perfectly fine if you need the full functionality of the instrumentation library. However if you only need to log some of the more simple telemetry like traces and events– then a lightweight and cross platform friendly option is to just call the Application Insights REST API directly from PowerShell and bypass client instrumentation libraries.
Using a web trace tool like fiddler we can watch the traffic that the AI instrumentation library is sending and then write helper functions that mimic that traffic.
Source Code
I wrote 3 helper functions for the most common Track operations I use on a regular basis. You can find the source code for these functions in my AzurePowerShellUtilityFunctions module on Github. Here are the examples and what they map to in the instrumentation library:
Function | Client Lib Function | Source Link |
Send-AppInsightsTraceTelemetry | TrackTrace() | Link |
Send-AppInsightsEventTelemetry | TrackEvent() | Link |
Send-AppInsightsExceptionTelemetry | TrackException() | Link |
Example Usage
Download the module source code from Github, import it into your current session, then just call the function.
# assumes your module was downloaded to C:\source Import-Module C:\Source\AzurePowerShellUtilityFunctions\AzurePowerShellUtilityFunctions.psd1 # plug in your AI instrumentation key, trace message, and severity. Send-AppInsightsTraceTelemetry -InstrumentationKey '<guid>' -Message 'This is an information logging message.' -Severity Information
You can also optionally specify custom properties that get logged with any of these operations. Here is an example for a custom event:
# log a custom event with extra custom properties Send-AppInsightsEventTelemetry -InstrumentationKey '<guid>' -EventName 'MyApplicationEvent1' -CustomProperties @{ 'CustomProperty1'='abc'; 'CustomProperty2'='xyz' }