我有一个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中看到一些遥测,但不能看到自定义事件。例如,我可以看到每次TestFunctions.TelemetryTest()
运行时出现的请求以及在WebJob初始化期间的各种跟踪。
我可能没有正确配置或没有以正确的方式获取TelemetryClient
,但我找不到任何关于在WebJobs中跟踪自定义事件的文档。
任何帮助,将不胜感激。
尝试显式设置instrumentationkey:
tc.Context.InstrumentationKey = "<your_key>";
根据the docs,您应该可以使用密钥
System.Environment.GetEnvironmentVariable(
"APPINSIGHTS_INSTRUMENTATIONKEY", EnvironmentVariableTarget.Process)
如果您已设置应用程序洞察集成。