我在玩一點Azure功能:大多數情況下,我嘗試將現有的Webjob移植到Azure函數,現在是時候讓我將Application Insights集成到我的一個函數中。攔截Azure功能主機關閉:刷新應用程序洞察TelemetryClient
所以基本上我只需要TelemetryClient
的一個實例,但是這個假設我能夠在應用程序停止時刷新內存緩衝區。
我已經使用了TimerTrigger,但它只是用於測試目的。
我引用的Microsoft.ApplicationInsights NuGet包(from this SO post)和我run.csx
文件看起來像這樣:
using System;
using Microsoft.ApplicationInsights;
using Microsoft.Azure.WebJobs;
public static void Run(TimerInfo myTimer, TraceWriter log)
{
MyTimerJob.TelemetryClient.TrackEvent("AzureFunctionTriggered");
log.Verbose($"C# Timer trigger function executed at: {DateTime.Now}");
}
public static class MyTimerJob
{
public static readonly TelemetryClient TelemetryClient;
static MyTimerJob(){
TelemetryClient = new TelemetryClient()
{ InstrumentationKey = "MyInstrumentationKey" };
// When it shutdowns, we flush the telemty client.
new WebJobsShutdownWatcher().Token.Register(() =>
{
TelemetryClient.TrackEvent("TelemetryClientFlush");
TelemetryClient.Flush();
});
}
}
這個實現是一個有點棘手...
- 我有一個靜態
TelemetryClient
以確保我將重用相同的實例。 - 我嘗試使用
WebJobsShutdownWatcher
來檢測主機何時停止,以便我可以刷新TelemetryClient。
要模擬應用程序關閉,我在下面的Web應用程序創建一個應用程序"test"
設置,我修改它時,我想在主機重新啓動:
不幸的是,這並不工作......我沒看到名字"TelemetryClientFlush"
任何情況下從應用程序分析信息中心:
所以我現在想知道當azure函數主機停止時是否有任何方法來攔截?
能否請你加$日誌語句將關閉回調確認代碼運行在所有。查看WebJobsShutdownWatcher源代碼,需要遵循幾個條件才能執行關機回調:https://github.com/Azure/azure-webjobs-sdk/blob/master/src/Microsoft.Azure.WebJobs。主機/ WebjobsShutdownWatcher.cs –