Use Azure Application Insights with Azure WebJob

大城市里の小女人 提交于 2019-11-30 08:01:11

I have written a console application that tracks events and metrics via Application Insights, and I figure a WebJob won't be all that different, by adding the following NuGet packages:

  • Microsoft.ApplicationInsights
  • Microsoft.ApplicationInsights.TraceListener (this may not be required)

My ApplicationInsights.config looks like this:

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

And the simple program does this:

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

There is also this: Application Insights on Windows Desktop apps, services and worker roles

Since the above answer is 2 years old and many things have changed since then. Now there is nuget package available for Application insights integration with Azure Webjobs. You need to install below packages:

  1. Microsoft.Azure.WebJobs.Logging.ApplicationInsights (Currently in beta)
  2. Microsoft.Extensions.Logging
  3. Microsoft.Extensions.Logging.Console

Configure JobHostConfiguration as below:

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

See full post on this here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!