Tho*_*mas 5 c# azure-webjobs azure-webjobssdk azure-application-insights azure-functions
我正在使用 Azure Function:主要是我尝试将现有的 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();
});
}
}
Run Code Online (Sandbox Code Playgroud)
这个实现有点棘手......
TelemetryClient来确保我将重用同一个实例。WebJobsShutdownWatcher来检测主机何时停止,以便我可以刷新 TelemetryClient。为了模拟应用程序关闭,我"test"在底层 Web 应用程序中创建了一个应用程序设置,并在我希望主机重新启动时修改它:
不幸的是,这不起作用......我"TelemetryClientFlush"在应用洞察仪表板中没有看到任何带有名称的事件:
所以我现在想知道有没有什么办法可以在azure function host停止的时候拦截?
除了 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}");
}
Run Code Online (Sandbox Code Playgroud)