Azure Functions and Application Insights Integration In dotnet isolated and in-process

Currently Azure Functions for dotnet available in two type of hosting. One is in process and another out of process or dotnet isolated.

This article focus on Azure Functions and Application Insights Integration for dotnet isolated mode but I will try to explain why this is required and for this I will start with Azure Function in-process mode.

Tools

  • Visual Studio 2022 ( Any Edition and I am using Visual Studio 2022 Community Edition)
  • Azure Function v4
  • Azure Subscription

Scenario

For this sample, Azure Function will try to access Azure Storage Account. We expect that if Azure Application Insights is enable then we can track the dependency for this.

image.png

In-Process Azure Functions

For this mode, It is quite simple. At the time of Function App creation make sure you enable Monitor mode and configure application insights.

image.png

Following is my sample function. That just create file based on content of request and name from url.

[FunctionName("SaveToStorage")]
        public static async Task<IActionResult> SaveToStorage(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "SaveToStorage/{name}")] HttpRequest req,
            [Blob("sampledata/{name}", FileAccess.Write)] Stream samplefile,            
            string name,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");           

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            await samplefile.WriteAsync(System.Text.Encoding.UTF8.GetBytes(requestBody));

            string responseMessage = $"File {name} save successfully.";

            return new OkObjectResult(responseMessage);
        }

Now if I look application insights for map then It display like this.

image.png

dotnet isolated mode or out of process Azure Functions

  • For Application Insights, same configuration required to enable integration.

  • Following is the sample Function. This is doing same thing that It is used to do in in-process mode but It required to address differently. This detail is not in scope for this article.

public class DotnetIsolatedFunctions
    {
        private readonly ILogger _logger;
        public DotnetIsolatedFunctions(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<DotnetIsolatedFunctions>();
        }

        [Function("SaveToStorage")]       
        public async Task<MyOutputType> SaveToStorage(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "SaveToStorage/{name}")] HttpRequestData req)
        {
            _logger.LogInformation("C# HTTP trigger function processed a request.");

            // Content to store in Storage
            var data = await req.ReadAsStringAsync();

            var response = req.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add("Content-Type", "text/plain; charset=utf-8");
            response.WriteString("Welcome to Azure Functions!");

            return new MyOutputType()
            {
                 HttpResponse = response,
                 Data = data
            };
        }

        public class MyOutputType
        {
            // This is how output binding needs to address.
            [BlobOutput("sampledata/{name}")]
            public string Data { get; set; }
            public HttpResponseData HttpResponse { get; set; }
        }
    }
  • Let's upload and check how application insight display in application map.
  • It looks something like this.

image.png

  • This is clearly evident that It is missing call to storage dependency.

Solution

  • To achieve same things as for Azure Functions In-process, there are some extra steps required.

  • Add Nuget package.

dotnet add package Microsoft.ApplicationInsights.WorkerService
  • Once this is done, It required to update host in program.cs. Now it will look something like this.
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices(services =>
    {
        services.AddApplicationInsightsTelemetryWorkerService();
    })
    .Build();

host.Run();
  • Now Let's upload again and check.

image.png

  • Now it display dependency properly.

Source Code

Download

How to run
  • In local.settings.json add storage connection. (same for in-process mode)
{
    "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "<<your storage connection string>>",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated"
  }
}

Summary

  • In-process mode, there is no extra step required to integrate with Azure ApplicationInsights.
  • Out-of-process or isolated mode, there is extra step required as mention above.
  • Also this will not only track Storage account dependency but It will display all types of dependency like SQL Server, Service bus etc.