从 Powershell 运行 Inside Webjob 写入 App Insights

Write to App Insights from Powershell Running Inside Webjob

我是 运行 使用此处概述的过程的 PowerShell 脚本: https://blogs.msdn.microsoft.com/nicktrog/2014/01/22/running-powershell-web-jobs-on-azure-websites/

我还在脚本中捕获错误并使用此处的方法将它们记录到 Application Insights: https://www.c-sharpcorner.com/article/using-azure-application-insights-in-powershell/

当代码运行时,我通过在脚本中引入错字来强制出错。异常被捕获并且 TrackException() 调用没有问题发生,但是没有日志条目进入应用程序洞察力! 我在本地尝试了 运行 相同的脚本,它的日志记录很好。

示例脚本:

$rootPath = ($env:webroot_path)
Add-Type -Path "$rootPath\bin\Microsoft.ApplicationInsights.dll"
$appInsightsClient = New-Object Microsoft.ApplicationInsights.TelemetryClient
$appInsightsClient.InstrumentationKey = "the-key"


try {
    $lastSuccessDate = Get-Dates "1/1/1900"
} catch {
    [Console]::WriteLine($_.Exception.Message)
    $telemetryException = New-Object "Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry"
    $telemetryException.Exception = $_.Exception
    $appInsightsClient.TrackException($telemetryException)

    Exit 1
}

为了让异常更新ApplicationInsights,您需要将Flush()添加到TelemetryClient

添加:

$appInsightsClient.TrackException($TelException)
$appInsightsClient.Flush()