将 Azure Application Insights 与 Azure WebJob 结合使用

Use Azure Application Insights with Azure WebJob

Azure 文档涵盖了很多将 Azure Application Insights 集成到不同应用程序类型的示例,例如 ASP.NET、Java 等。但是,该文档没有显示任何集成应用程序的示例深入了解 Azure WebJob。

是否有人 link 有涵盖如何将 Azure Application Insights 集成到构建为控制台应用程序的 Azure WebJob 的示例或文章?

我编写了一个通过 Application Insights 跟踪事件和指标的控制台应用程序,我认为通过添加以下 NuGet 包,WebJob 不会有太大不同:

  • Microsoft.ApplicationInsights
  • Microsoft.ApplicationInsights.TraceListener(这可能不是必需的)

我的 ApplicationInsights.config 看起来像这样:

<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
    <TelemetryModules>
        <Add Type="Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.DiagnosticsTelemetryModule, Microsoft.ApplicationInsights" />
    </TelemetryModules>
</ApplicationInsights>

简单的程序是这样做的:

TelemetryConfiguration.Active.InstrumentationKey = "the_key";
TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = true;

var tc = new TelemetryClient();
tc.TrackRequest("Track Some Request", DateTimeOffset.UtcNow, new TimeSpan(0, 0, 3), "200", true);
tc.TrackMetric("XYZ Metric", 100);
tc.TrackEvent("Tracked Event");

tc.Flush(); //need to do this, otherwise if the app exits the telemetry data won't be sent

还有这个:Application Insights on Windows Desktop apps, services and worker roles

由于上述答案已有 2 年历史,自那以后很多事情都发生了变化。现在有 nuget 包可用于 Application insights 与 Azure Webjobs 的集成。您需要安装以下软件包:

  1. Microsoft.Azure.WebJobs.Logging.ApplicationInsights(目前处于测试阶段)
  2. Microsoft.Extensions.Logging
  3. Microsoft.Extensions.Logging.控制台

按如下方式配置 JobHostConfiguration:

string instrumentationKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY");
if (!string.IsNullOrEmpty(instrumentationKey))
{
      // build up a LoggerFactory with ApplicationInsights and a Console Logger
       config.LoggerFactory = new LoggerFactory().AddApplicationInsights(instrumentationKey, null).AddConsole();
       config.Tracing.ConsoleLevel = TraceLevel.Off;
}

在此 here

上查看完整 post