Search code examples
c#loggingazure-functionsazure-application-insights.net-8.0

Azure Function logging to App Insights won't log below warning level


I have created a new Azure Function app with several functions in it, but I cannot for the life of me get it to print out Information logs.

I have some existing .NET 3.1 functions (created years ago) running on an older runtime (v3), and I have my hosts.json file set to this:

{
  "version": "2.0",
  "logging": {
    "LogLevel": {
      "Default": "None",
      "Function.MyFunc.User": "Information",
      "Function.MyFunc": "Warning"
    },
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": false
      }
    }
  }
}

This works PERFECTLY for my existing functions. It prints out errors thrown by the function and also logs the information I produce using log.LogInformation(xxx).

The issue I'm having is that now I've created some new functions using .NET 8 and the newer runtime (v4), I just can't get them to log in the same way as my existing functions. For the record, I have scoured through every StackOverflow question I can find (like this), and I've read through the MS docs which details how to do it. Unfortunately, nothing I have tried works for me. Here is my new function, the host file, and the program file:

namespace XXX.Azure.FunctionApps.Mailbox.Functions
{
    public class GetMailFolders
    {
        private readonly ILogger<GetMailFolders> _logger;

        public GetMailFolders(ILogger<GetMailFolders> logger)
        {
            _logger = logger; // also tried loggerFactory version
        }

        [Function("GetMailFolders")]
        public IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req)
        {
            _logger.LogTrace("Trace Msg");
            _logger.LogDebug("Debug Msg");
            _logger.LogInformation("Information Msg");
            _logger.LogWarning("Warning Msg");
            _logger.LogError("Error Msg");
            _logger.LogCritical("Critical Msg");

            return new OkObjectResult(null);
        }
    }
}

host.json:

{
  "version": "2.0",
  "logging": {
    "logLevel": {
      "Function.GetMailFolders": "Trace",
      "Function.GetMailFolders.User": "Trace"
    },
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": false
      }
    }
  }
}

Program.cs:

using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

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

host.Run();

I have tried about 20 different combinations. Including the namespace of the function, "Function.GetMailFolders", "Function.GetMailFolders.User", "default", "Function", etc. Some settings have altered the verbosity of the function initialisation logs, and request logs, etc. But nothing I set will have any impact on the logs that I try to print in application insights, which is:

enter image description here

Even if I attempt to disable the logs completely, those three lines appear every time. No matter what I've tried, warning and above are the only ones that will ever show up.


Solution

  • Application insights captures only above Warning severity level by default. You need to disable it in part of service configuration.

    For reference check this MS document.

    For Information log, adding this part in Program.cs it worked:

    .ConfigureLogging(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);
                }
            });
        })
    

    #My Code: Function1.cs:

    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Azure.Functions.Worker;
    using Microsoft.Extensions.Logging;
    
    namespace FunctionApp1
    {
        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.");
                _logger.LogInformation("This is Information log");
                _logger.LogWarning("This is Warning log");
                _logger.LogError("This is Error log");
                _logger.LogCritical("This is Critical log");
                return new OkObjectResult("Welcome to Azure Functions!");
            }
        }
    }
    
    

    Program.cs:

    using Microsoft.Azure.Functions.Worker;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    using Microsoft.Extensions.Logging;
    
    var host = new HostBuilder()
        .ConfigureFunctionsWebApplication()
        .ConfigureServices(services =>
        {
            services.AddApplicationInsightsTelemetryWorkerService();
            services.ConfigureFunctionsApplicationInsights();
        })
        .ConfigureLogging(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();
    

    host.json:

    {
        "version": "2.0",
      "logging": {
        "applicationInsights": {
          "samplingSettings": {
            "isEnabled": true,
            "excludedTypes": "Request"
          },
          "enableLiveMetricsFilters": true
        }
      }
    }
    

    OUTPUT:

    Trace and below:

    For Getting below Information severity level log add this in Program.cs, it works:

    .ConfigureAppConfiguration((hostContext, config) =>
    {
        config.AddJsonFile("host.json", optional: true);
    })
    .ConfigureLogging((hostingContext, logging) =>
    {
        logging.AddApplicationInsights(console =>
        {
            console.IncludeScopes = true;
        });
    
        logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
    })
    

    Program.cs:

    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();
        })
        .ConfigureLogging(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);
                }
            });
        })
        .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();
    

    Function.cs:

    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Azure.Functions.Worker;
    using Microsoft.Extensions.Logging;
    
    namespace FunctionApp1
    {
        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.");
                _logger.LogDebug("This is Debug log");
                _logger.LogTrace("This is Trace Log");
                _logger.LogInformation("This is Information log");
                _logger.LogWarning("This is Warning log");
                _logger.LogError("This is Error log");
                _logger.LogCritical("This is Critical log");
                return new OkObjectResult("Welcome to Azure Functions!");
            }
        }
    }
    

    host.json;

    {
        "version": "2.0",
      "logging": {
        "logLevel": {
          "default": "Trace"
        },
        "applicationInsights": {
          "samplingSettings": {
            "isEnabled": true,
            "excludedTypes": "Request"
          },
          "enableLiveMetricsFilters": true
        }
      }
    }
    

    OUTPUT:

    For Reference check this SO Answer