Search code examples
azure-functionsazure-application-insights

How to get Application Insights TelemetryClient in Isolated .NET 7 Azure function?


I create an Azure Function from the newest Visual Studio template and deploy it to Azure. I have setup Application Insights in the Azure portal so the actual code doesn't yet know about AppInsights. So far everything works.

Now I want to log some custom telemetry. What do I need to do?

I've tried the following:

  • Taking a dependency on TelemetryClient
    • DI cannot resolve it
  • Taking a dependency on TelemetryConfiguration
    • DI cannot resolve it
  • Taking a dependency on IOptions<TelemetryConfiguration> and creating TelemetryClient from options.Value
    • Nothing happens. I guess just having the APPINSIGHTS_INSTRUMENTATIONKEY key in configuration is not enough

What to do?


Solution

  • App Insights, with automatic dependency collection and correlation between application calling each other, can be used by adding the following package to the Azure Function.No other AppInsights related packages are needed to be installed.

    Microsoft.Azure.Functions.Worker.ApplicationInsights 1.0.0-preview4

    and adding having the following program.cs

    using Microsoft.Extensions.Hosting;
    using Microsoft.Azure.Functions.Worker;
    
    var host = new HostBuilder()
      .ConfigureFunctionsWorkerDefaults((_, builder) =>
      {
          builder
              .AddApplicationInsights()
              .AddApplicationInsightsLogger();
      })
      .Build();
    
    host.Run();
    

    Then TelemetryClient can be used though DI and all "normal" data will be collected out of the box.

    Note that the package is still in preview.