Quantcast
Channel: mattfrear – Matt's work blog
Viewing all articles
Browse latest Browse all 53

Logging to Application Insights with ILogger in Azure functions on .NET 8

$
0
0

Today I couldn’t figure out why any of my ILogger messages in my Azure Function weren’t appearing in Application Insights. According to my research they should appear as Trace messages.

logger.LogInformation("Message ID: {id}", message.MessageId);

 

I tried various Log Level tweaks to host.json to no avail.

Fortunately one of my colleagues (hi Ivan!) had previously had the same issue, and he’d already found the fix, which is documented here.

Turns out that dotnet-isolated Functions work a bit differently.


var host = new HostBuilder()
    .ConfigureFunctionsWebApplication()
    .ConfigureServices((context, services) =>
    {
        services.AddApplicationInsightsTelemetryWorkerService();
        services.ConfigureFunctionsApplicationInsights();
    })
    .ConfigureLogging(logging =>
    {
        logging.Services.Configure<LoggerFilterOptions>(options =>
        {
            // https://learn.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide?tabs=windows#managing-log-levels
            // By default, the Application Insights SDK adds a logging filter that instructs the logger to capture only warnings and more severe logs.
            // To disable this behavior, remove the filter rule as part of service configuration:
            var defaultRule = options.Rules.FirstOrDefault(rule => rule.ProviderName == "Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider");
            if (defaultRule is not null)
            {
                options.Rules.Remove(defaultRule);
            }
            // Set log level to Information so that we don't log traces
            var loggingRule = new LoggerFilterRule("PropertySync", null, LogLevel.Information, null);
            options.Rules.Add(loggingRule);
        });
    })
    .Build();

azure application insights


Viewing all articles
Browse latest Browse all 53

Trending Articles