skip to Main Content

I am currently writing an Azure Function and had a look into the documentation of Azure Function.
This documentation suggest to remove the default rule for application insights: https://learn.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide?tabs=windows#managing-log-levels

The rest of your application continues to work with ILogger and ILogger. However, by default, the Application Insights SDK adds a logging filter that instructs the logger to capture only warnings and more severe logs. If you want to disable this behavior, remove the filter rule as part of service configuration

LoggerFilterRule defaultRule = options.Rules.FirstOrDefault(rule => rule.ProviderName == "Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider");
if (defaultRule is not null)
{
   options.Rules.Remove(defaultRule);
}

However this documentation suggest doing it via the host.json https://learn.microsoft.com/en-us/azure/azure-monitor/app/worker-service#ilogger-logs

It’s important to note that the following example doesn’t cause the Application Insights provider to capture Information logs. It doesn’t capture it because the SDK adds a default logging filter that instructs ApplicationInsights to capture only Warning logs and more severe logs. Application Insights requires an explicit override.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    },
    "applicationInsights": {
       "logLevel": {
          "Default": "Information"
    }
  }
}

But this seems to have absolute no effect on the default filter rule added when I debug and check which rules are loaded. Even after the updates in the host.json it seems this filter rule is still set to warnings.

Image from Visual Studio Debugger showing the default app insights rule - log level set to warning

So the question is really, is there any way to control that behavior over the host.json/configuration at all?

2

Answers


  1. Easiest way to set the ApplicationInsights log level to Information is to add this line to your local.settings.json:

    "values": {
      "Logging:ApplicationInsights:LogLevel:Default": "Information"
    }
    

    On local environment you set this setting in local.settings.json (inside values object).
    On Azure you set thise setting in your function’s application settings.

    Note that this is not a host or binding related configuration, this is roughly speaking a configuration of your injected services. That’s why you do not set such settings in host.json!

    Explanation:

    By default, the ApplicationInsights provider catches by default only Warning and Error logs. However, it can be changed by configuration. This configuration controls the behavior:

    {
      "Logging": {
        "ApplicationInsights": {
          "LogLevel": {
            "Default": "Information"
          }
        }
      }
    }
    

    You need to configure Logging:ApplicationInsights:LogLevel explicitely. Setting top level Logging:LogLevel only, would have no effect because it would be overwritten by defaults coming from Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider (which the other document you mentioned suggest to remove). Instead of removing it you can configure it by setting Logging:ApplicationInsights:LogLevel.

    Note that not always a complex JSON config structure is supported. The configuration in general is always key-value pairs. The JSON presented above, in runtime would be normally converted to "Logging:ApplicationInsights:LogLevel:Default": "Default" pair. For Azure deployed functions you need to provide configuration in such inlined form (note that in some environments the : nesting separator needs to be changed to __, for example Azure KeyVault or Linux/Windows environment variables syntax differ too). The same is for for local functions host which reads local.settings.json.

    Login or Signup to reply.
  2. You can add the default log level using host.json file and making the below changes in program.cs file.

    {
        "version": "2.0",
        "logging": {
          "logLevel": {
            "Function.Function1": "Information"
          }
        }
    }
    
    using Microsoft.Azure.Functions.Worker;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    
    var host = new HostBuilder()
        .ConfigureFunctionsWebApplication()
        .ConfigureServices(services =>
        {
            services.AddApplicationInsightsTelemetryWorkerService();
            services.ConfigureFunctionsApplicationInsights();
            services.Configure<LoggerFilterOptions>(options =>
            {
                LoggerFilterRule defaultRule = options.Rules.FirstOrDefault(rule => rule.ProviderName == "Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider");
    
                if (defaultRule is not null)
                {
                    options.Rules.Remove(defaultRule);
                }
            });
        })
        .ConfigureAppConfiguration((hostContext, config) =>
        {
            config.AddJsonFile("host.json", optional: true);
        })
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddApplicationInsights(console =>
            {
                console.IncludeScopes = true;
            });
    
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
        })
        .Build();
    
    host.Run();
    

    I am using default .Net8 isolated function code as given below.

    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Azure.Functions.Worker;
    using Microsoft.Extensions.Logging;
    
    namespace _79026563
    {
        public class Function1
        {
            private readonly ILogger<Function1> _logger;
    
            public Function1(ILogger<Function1> logger)
            {
                _logger = logger;
            }
    
            [Function("Function1")]
            public IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequest req)
            {
                _logger.LogInformation("C# HTTP trigger function processed a request.");
                return new OkObjectResult("Welcome to Azure Functions!");
            }
        }
    }
    

    I am getting all the information logs as given below and it does work.

    enter image description here

    Azure Functions Core Tools
    Core Tools Version:       4.0.6280 Commit hash: N/A +421f0144b42047aa289ce691dc6db4fc8b6143e6 (64-bit)
    Function Runtime Version: 4.834.3.22875
    
    [2024-09-26T12:36:15.636Z] Found C:Users*****7902656379026563.csproj. Using for user secrets file configuration.
    [2024-09-26T12:36:18.749Z] Azure Functions .NET Worker (PID: 38560) initialized in debug mode. Waiting for debugger to attach...
    [2024-09-26T12:36:18.794Z] Worker process started and initialized.
    
    Functions:
    
            Function1: [GET,POST] http://localhost:7025/api/Function1
    
    For detailed output, run func with --verbose flag.
    [2024-09-26T12:36:23.854Z] Host lock lease acquired by instance ID '0000000000000000000000000D2022A4'.
    [2024-09-26T12:36:37.667Z] Executing 'Functions.Function1' (Reason='This function was programmatically called via the host APIs.', Id=9e791713-f046-4d2c-adc1-8f6130e3ad21)
    [2024-09-26T12:36:38.052Z] C# HTTP trigger function processed a request.
    [2024-09-26T12:36:38.058Z] Executing OkObjectResult, writing value of type 'System.String'.
    [2024-09-26T12:36:38.147Z] Executed 'Functions.Function1' (Succeeded, Id=9e791713-f046-4d2c-adc1-8f6130e3ad21, Duration=542ms)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search