如何在 Application Insights 中跟踪来自 Azure WebJobs 的自定义事件?

How do you track custom events from Azure WebJobs in Application Insights?

我有一个 Azure WebJobs (v2.2.0) 项目,我想使用 Application Insights (AI) 对其进行监控,并且我希望能够跟踪一些事件。在配置为使用 AI 的普通 Web 应用程序中,您可以使用以下命令:

TelemetryClient tc = new TelemetryClient();
tc.TrackEvent("EventName");

然而,这在 WebJob 的上下文中似乎不起作用!我已经按照 WebJob SDK repo 上的说明配置了我的 WebJob 项目,最终看起来像这样:

计划

using System.Configuration;
using System.Diagnostics;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;

namespace WebJobs
{
  public class Program
  {
    public static void Main()
    {
      JobHostConfiguration config = new JobHostConfiguration();
      config.UseTimers();

      using (LoggerFactory loggerFactory = new LoggerFactory())
      {
        string key = ConfigurationManager.AppSettings["webjob-instrumentation-key"];
        loggerFactory.AddApplicationInsights(key, null);
        loggerFactory.AddConsole();
        config.LoggerFactory = loggerFactory;
        config.Tracing.ConsoleLevel = TraceLevel.Off;

        if (config.IsDevelopment)                
          config.UseDevelopmentSettings();                

        JobHost host = new JobHost(config);

        host.RunAndBlock();
      }
    } 
  }
}

函数

这只是一个测试功能,半小时内每分钟运行。

using Core.Telemetry;
using Microsoft.ApplicationInsights;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Timers;
using System;
using System.Collections.Generic;

namespace WebJobs.Functions
{
  public class TestFunctions
  {
    public void TelemetryTest([TimerTrigger(typeof(Schedule))] TimerInfo timer)
    {
      TelemetryClient tc = new TelemetryClient();
      tc.TrackEvent("TelemetryTestEvent");
    }

    // schedule that will run every minute
    public class Schedule : DailySchedule
    {
        private static readonly string[] times =
        {
          "12:01","12:02","12:03","12:04","12:05","12:06","12:07","12:08","12:09","12:10",
          "12:11","12:12","12:13","12:14","12:15","12:16","12:17","12:18","12:19","12:20",
          "12:21","12:22","12:23","12:24","12:25","12:26","12:27","12:28","12:29","12:30"
        };

        public Schedule() : base(times) { }
    }
  }
}

这似乎部分起作用,因为我可以在 AI 中看到一些遥测数据,但看不到自定义事件。例如,我可以看到 Request 每次 TestFunctions.TelemetryTest() 运行s 和各种 Traces 在初始化期间出现网络作业。

我可能没有正确配置某些东西或者没有以正确的方式获取 TelemetryClient,但是我找不到任何关于在 WebJobs 中跟踪自定义事件的文档。

如有任何帮助,我们将不胜感激。

尝试显式设置检测键:

tc.Context.InstrumentationKey = "<your_key>";

根据the docs,您应该可以使用

获取密钥
System.Environment.GetEnvironmentVariable(
            "APPINSIGHTS_INSTRUMENTATIONKEY", EnvironmentVariableTarget.Process)

如果您已经设置了 Application Insights 集成。