gpt4 book ai didi

c# - 拦截 Azure 函数主机关闭 : Flush Application Insights TelemetryClient

转载 作者:太空狗 更新时间:2023-10-30 00:38:58 24 4
gpt4 key购买 nike

我正在尝试使用 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” 应用程序设置,并在我希望主机重新启动时修改它:

Azure Function - Application terminated log

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

Microsoft Application Insights - Custom Events dashboard

所以我现在想知道是否有任何方法可以在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com