Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

.NET 8 Isolated Logging to Application Insights I can't change LogLevel from Azure Environment Variables #2531

Open
JuanGRomeo opened this issue Jun 13, 2024 · 0 comments
Labels
area: migration Items related to migration from the in-process model Needs: Triage (Functions)

Comments

@JuanGRomeo
Copy link

What version of .NET does your existing project use?

.NET 6

What version of .NET are you attempting to target?

.NET 8

Description

Hello!

I managed successfully to migrate a .NET 6 In-Process Azure Function to .NET 8 isolated but I'm having issues configuring correctly Application Insights logs.

Currently the HostBuilder is configured in this way:

var host = new HostBuilder()
    .ConfigureAppConfiguration((context, config) =>
    {
        config.AddJsonFile("host.json", optional: true, reloadOnChange: true)
              .AddEnvironmentVariables();
    })
    .ConfigureFunctionsWebApplication()
    .ConfigureServices(services =>
    {
        services.AddApplicationInsightsTelemetryWorkerService();
        services.ConfigureFunctionsApplicationInsights();
        services.ConfigureAdeslasDirectoTestServiceExtensions();
    })
    .ConfigureLogging((context, logging) =>
    {
        logging.AddConfiguration(context.Configuration.GetSection("Logging"));
    })
    .ConfigureLogging((context, logging) =>
    {
        logging.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);
            }
        });
    })
    .Build();

host.Run();

The logging.AddConfiguration(context.Configuration.GetSection("Logging")); intention from that line was to register in the logging configuration what I have configured in the host.json in combination with the AddJsonFile call.

Additionally, I added the removal of the default Filter which prevents to log any other LogLevel instead of Warning and higher.

If I debug the Program.cs with that setup, I see how the only existing rules are the ones created based on the host.json configuration:

339272901-1a27c133-1f1b-43ea-86c2-b1262aa8d6fb

csproj looks like this:

<Project Sdk="Microsoft.NET.Sdk">
	<PropertyGroup>
		<TargetFramework>net8.0</TargetFramework>
		<AzureFunctionsVersion>v4</AzureFunctionsVersion>
		<OutputType>Exe</OutputType>
	</PropertyGroup>
	<ItemGroup>
		<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.ServiceBus" Version="5.19.0" />
		<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Timer" Version="4.3.1" />
		<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="6.0.9" />
		<FrameworkReference Include="Microsoft.AspNetCore.App" />
		<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.22.0" />
		<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.17.2" />
		<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore" Version="1.2.1" />
		<PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.22.0" />
		<PackageReference Include="Microsoft.Azure.Functions.Worker.ApplicationInsights" Version="1.2.0" />
	</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>

The code Function:

[Function(nameof(ProcessRisk))]
public async Task ProcessRisk(
[ServiceBusTrigger("topic", "subscription", Connection = "ServiceBusActivity")] 
string customerActivity)
{
    _logger.LogDebug("Log Debug");
    _logger.LogTrace("Log Trace");
    _logger.LogInformation("Log Info");
    _logger.LogWarning("Log Warn");
    _logger.LogError("Log Error");
    _logger.LogCritical("Log Critical");
}

the host.json

{
  "version": "2.0",
  "extensions": {
    "http": {
      "maxOutstandingRequests": -1,
      "maxConcurrentRequests": -1,
      "dynamicThrottlesEnabled": false
    }
  },
  "logging": {
    "logLevel": {
      "default": "Warning", 
      "Function": "Information", 
      "Host.Aggregator": "Error", 
      "Host.Results": "Information", 
      "Function.ProcessRisk": "Information", 
      "Function.ProcessRisk.User": "Error" 
    },
    "applicationInsights": {
      "samplingExcludedTypes": "Request",
      "samplingSettings": {
        "isEnabled": true
      }
    }
  }
}

And the result Logs on the App Insights:
image

If I change the parameter "AzureFunctionsJobHost__logging__logLevel__Function__ProcessRisk__User" value directly on Azure to Information I'm still only seeing the Logs attached on the image (Warning, Error & Critical) so i'm not able to increase o decrease the LogLevel.

Previously, I only added the script to remove the default rule on the Program.cs but only with that configuration the Function is always registering the Information Logs I wrote in the Function even if I have the LogLevel ("AzureFunctionsJobHost__logging__logLevel__Function__ProcessRisk__User") set to Error on Azure. That's why I tried to add the ConfigureLogging by taking values from the host.json file but is not working fine.

What is the correct configuration to be able to configure LogLevels based on Azure Environment variables?

References I used:

Thanks.

Project configuration and dependencies

No response

Link to a repository that reproduces the issue

No response

@JuanGRomeo JuanGRomeo added the area: migration Items related to migration from the in-process model label Jun 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area: migration Items related to migration from the in-process model Needs: Triage (Functions)
Projects
None yet
Development

No branches or pull requests

1 participant