在Azure WebJob中使用Azure应用程序洞察

本文关键字:Azure 应用程序 洞察 WebJob | 更新日期: 2023-09-27 18:12:01

Azure文档涵盖了许多将Azure应用程序见解集成到不同应用程序类型的示例,例如ASP。. NET、Java等。然而,文档并没有展示任何将Application Insights集成到Azure WebJob的示例。

有没有人有链接到一个例子或文章,涵盖如何集成Azure应用程序洞察到Azure WebJob作为一个控制台应用程序构建?

在Azure WebJob中使用Azure应用程序洞察

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

  • 微软。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

还有这个:Windows桌面应用程序,服务和worker角色的应用程序见解

因为上面的答案是两年前的,从那以后很多事情都发生了变化。现在有一个nuget包可用于应用程序洞察与Azure Webjobs的集成。您需要安装以下软件包:

  1. Microsoft.Azure.WebJobs.Logging。ApplicationInsights(目前在测试中)
  2. Microsoft.Extensions。日志
  3. Microsoft.Extensions.Logging.Console

配置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;
}

点击这里查看全文