我正在尝试使用 Azure Functions:我主要尝试将现有的 Web 作业迁移到 Azure Functions,现在是时候将 Application Insights 集成到我的一个函数中了。
所以基本上我只需要一个 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 函数主机停止时进行拦截?
最佳答案
除了 Mathew 描述的内容之外,您可能还想尝试一下我们会根据要求传递的取消 token 。
如果您将 CancellationToken
类型的参数添加到您的函数,我们将传递一个 token ,当主机在正常情况下关闭时,该 token 将发出信号。使用它可以让您接近您需要的东西:
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}");
}
关于c# - 拦截 Azure 函数主机关闭 : Flush Application Insights TelemetryClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36760241/