Azure Function App Insights logging scopes do not seem to work

Louis van Alphen 25 Reputation points
2023-11-26T12:39:28.8133333+00:00

I have a minimal HTTP triggered Azure Function to test the inclusion of logging scopes in AppInsights.

The Program.cs as as follows:

using Microsoft.Extensions.Hosting;
 
var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .Build();
 
host.Run();

host.json is

{
  "version": "2.0",
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  }
}

The function body is

using System.Net;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;

namespace TestAzureFunctionLoggingScopes
{
  public class TestLoggingScopes
  {
    public TestLoggingScopes(ILogger<TestLoggingScopes> logger)
    {
      this.logger = logger;
    }

    [Function("TestLoggingScopes")]
    public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req)
    {
      using IDisposable scope = logger.BeginScope(new Dictionary<string, object> { ["MyScope"] = "MyLog" });

      logger.LogInformation($"C# HTTP trigger function processed a request. InvocationId: {req.FunctionContext.InvocationId}");

      var response = req.CreateResponse(HttpStatusCode.OK);

      response.WriteString($"Welcome to Azure Functions. InvocationId: {req.FunctionContext.InvocationId}");

      return response;
    }

    private readonly ILogger<TestLoggingScopes> logger;
  }
}

I am expection the AppInsight log entry to contain a CustomDimension prop__MyScope with value "MyLog" but it is not present.

enter image description here

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
{count} votes

1 answer

Sort by: Most helpful
  1. Ryan Hill 30,326 Reputation points Microsoft Employee Moderator
    2023-11-27T16:03:47.88+00:00

    Hi @Louis van Alphen

    Your logging was done outside the scope. The logging you're doing should be done in between the braces { } to show scopes. It should be written as follow:

    using (_logger.BeginScope("hello scope"))
    {
        _logger.LogError("An example of an Error level message");
    }
    

    Your current implementation only initializes scopes object which gets disposed after the Run method finishes. See Application Insights logging with .NET - Azure Monitor | Microsoft Learn for more info.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.