7

我正在使用 Azure Functions:大多数情况下,我尝试将现有的网络作业迁移到 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。

为了模拟应用程序关闭,我"test"在底层 Web 应用程序中创建了一个应用程序设置,并在我希望主机重新启动时对其进行了修改:

Azure 函数 - 应用程序终止日志

不幸的是,这不起作用......我没有"TelemetryClientFlush"从应用洞察仪表板中看到任何带有名称的事件:

Microsoft Application Insights - 自定义事件仪表板

所以我现在想知道当天蓝色功能主机停止时是否有任何方法可以拦截?

4

2 回答 2

6

除了 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}");
}
于 2016-04-22T12:25:58.727 回答
3

虽然 Azure Functions 确实在 WebJobs SDK 之上运行,但它不在传统的Kudu WebJobs基础架构下运行。WebJobsShutdownWatcher实际上依赖于 Kudu 主机的功能,特别是WEBJOBS_SHUTDOWN_FILE. 基本上,当 Kudu 主机关闭时,它会触及观察者正在监视的这个文件。由于没有触及此类文件,因此不会触发您的代码。

我们可以进行更改以允许观察者按原样工作,或者我们可以为函数引入一种新模式。我在我们的仓库中记录了一个问题,在这里跟踪这个建议。我认为这个场景很重要,我们会考虑一下。

于 2016-04-21T15:52:45.660 回答