拦截Azurefunction主机关闭:刷新应用程序洞察TelemetryClient

我正在使用Azurefunction:我主要尝试将现有的webjob迁移到Azurefunction,现在是时候将Application Insights集成到我的一个function中了。

所以基本上我只需要一个TelemetryClient实例,但这假设我能够在应用程序停止时刷新内存缓冲区。

我使用过TimerTrigger,但它仅用于测试目的。

我引用了Microsoft.ApplicationInsights nuget包( 来自这篇SOpost ),我的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  - 自定义事件仪表板

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

除了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 Functions确实在WebJobs SDK之上运行,但它不能在传统的Kudu WebJobs基础结构下运行。 WebJobsShutdownWatcher实际上依赖于Kudu主机的function,特别是WEBJOBS_SHUTDOWN_FILE指示的sentinel文件。 基本上当Kudu主机关闭时,它会触及观察者正在监视的文件。 由于没有触及此类文件,因此不会触发您的代码。

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