skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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.


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

    I have reproduced in my environment and got expected results as below:

    .csproj:

    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <TargetFramework>net7.0</TargetFramework>
        <AzureFunctionsVersion>v4</AzureFunctionsVersion>
        <OutputType>Exe</OutputType>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
      </PropertyGroup>
      <ItemGroup>
        <PackageReference Include="Microsoft.ApplicationInsights.WindowsServer" Version="2.21.0" />
        <PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.21.0" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.10.0" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.13" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.7.0" />
        <PackageReference Include="Microsoft.Azure.WebJobs.Logging.ApplicationInsights" Version="3.0.35" />
      </ItemGroup>
      <ItemGroup>
        <None Update="host.json">
          <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </None>
        <None Update="local.settings.json">
          <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
          <CopyToPublishDirectory>Never</CopyToPublishDirectory>
        </None>
      </ItemGroup>
      <ItemGroup>
        <Using Include="System.Threading.ExecutionContext" Alias="ExecutionContext" />
      </ItemGroup>
    </Project>
    

    local.settings.json:

    {
        "IsEncrypted": false,
      "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
        "APPINSIGHTS_INSTRUMENTATIONKEY": "308f2xxxxx039"
      }
    }
    

    Function.cs:

    using System.Net;
    using Microsoft.ApplicationInsights.Extensibility;
    using Microsoft.ApplicationInsights;
    using Microsoft.Azure.Functions.Worker;
    using Microsoft.Azure.Functions.Worker.Http;
    using Microsoft.Extensions.Logging;
    using Microsoft.ApplicationInsights.DataContracts;
    using static System.Runtime.InteropServices.JavaScript.JSType;
    
    namespace FunctionApp23
    {
        public class Function1
        {
            public readonly TelemetryClient _tc;
            
    
            public Function1(TelemetryClient telClient)
            {
                _tc = telClient;
                
            }
            [Function("Function1")]
            public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req, ILogger log)
            {
                _tc.TrackEvent("Function is running Rithwik");
    
                var response = req.CreateResponse(HttpStatusCode.OK);
                response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
    
                response.WriteString("Welcome to Azure Functions!");
    
                _tc.TrackEvent("Function is Completed Rithwik");
    
                return response;
            }
        }
    }
    

    host.json:

    {   "version": "2.0",   "logging": {
        "applicationInsights": {
          "samplingSettings": {
            "isEnabled": true,
            "excludedTypes": "Request"
          }
        }   
      }
    }
    

    Output:

    enter image description here

    enter image description here

    Then in Portal:

    enter image description here

    enter image description here

    Try to follow the above steps to get telemetry client traces in portal and you will get required results as I have got.

    Program.cs:

    using Microsoft.ApplicationInsights.Extensibility;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    
    
    var host = new HostBuilder()
        .ConfigureFunctionsWorkerDefaults()
        .ConfigureServices(services =>
        {
            services.AddApplicationInsightsTelemetryWorkerService();
        })
        .Build();
    
    host.Run();
    
    
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search