簡體   English   中英

攔截Azure功能主機關閉:刷新應用程序洞察TelemetryClient

[英]Intercept Azure Function Host Shutdown: Flush Application Insights TelemetryClient

我正在使用Azure功能:我主要嘗試將現有的webjob遷移到Azure Functions,現在是時候將Application Insights集成到我的一個功能中了。

所以基本上我只需要一個TelemetryClient實例,但這假設我能夠在應用程序停止時刷新內存緩沖區。

我使用過TimerTrigger,但它僅用於測試目的。

我引用了Microsoft.ApplicationInsights nuget包( 來自這篇SO帖子 ),我的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"應用程序設置,並在我希望主機重新啟動時對其進行修改:

Azure功能 - 應用程序終止日志

不幸的是,這不起作用......我從app insights儀表板中看不到任何名為"TelemetryClientFlush"事件:

Microsoft Application Insights  - 自定義事件儀表板

所以我現在想知道當天藍色功能主機停止時是否有任何方法可以攔截?

除了Mathew所描述的內容之外,您可能想要使用我們將要求的取消令牌。

如果向函數添加CancellationToken類型參數,我們將傳入一個令牌,當主機在正常情況下關閉時,該令牌將發出信號。 使用它可以讓您接近您需要的:

using System;
using System.Threading;
using Microsoft.ApplicationInsights;

public static readonly TelemetryClient TelemetryClient = new  TelemetryClient(){ InstrumentationKey = "MyInstrumentationKey" };
public static bool first = true;
public static void Run(TimerInfo myTimer, TraceWriter log, CancellationToken token)
{
    if(first){
        token.Register(() =>
        {
            TelemetryClient.TrackEvent("TelemetryClientFlush");
            TelemetryClient.Flush();
        });
        first = false;
    }

    TelemetryClient.TrackEvent("AzureFunctionTriggered");
    log.Verbose($"C# Timer trigger function executed at: {DateTime.Now}");
}

雖然Azure功能確實在WebJobs SDK之上運行,但它不能在傳統的Kudu WebJobs基礎結構下運行。 WebJobsShutdownWatcher實際上依賴於Kudu主機的功能,特別是WEBJOBS_SHUTDOWN_FILE指示的sentinel文件。 基本上當Kudu主機關閉時,它會觸及觀察者正在監視的文件。 由於沒有觸及此類文件,因此不會觸發您的代碼。

我們可以進行更改以允許觀察者按原樣工作,或者我們可能會為函數引入新模式。 跟蹤此建議的回購中記錄了一個問題。 我認為情景很重要,我們會考慮一下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM