.netazurelogfile

Azure Functions Application Insights: ILogger Messages Not Appearing in Logs


I have two Azure Functions: one using Durable Orchestration and another using a Queue Trigger. Both functions utilize ILogger for logging with log.LogInformation and log.LogWarning, and also have Console.WriteLine statements for output.

When I deploy and trigger both function apps, I can see the log information and console values in the Monitoring -> Log Stream section of the Azure portal. However, when I try to export these logs via Application Insights, I encounter an issue.

In Application Insights -> Logs, I run the following query to retrieve logs:

union isfuzzy=true
    availabilityResults,
    requests,
    exceptions,
    pageViews,
    traces,
    customEvents,
    dependencies
| order by timestamp desc

I get a list of log details, but only the Console.WriteLine messages are available. The log.LogInformation messages are missing.

My host.json file has the following log levels configured:

{
  "version": "2.0",
  "logging": {
    "logLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

Despite this, the log.LogInformation entries are not appearing in Application Insights. Here is my Program.cs configuration for setting up Application Insights in the .NET isolated process:


using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Text.Json;
using System.Text.Json.Serialization;

var host = new HostBuilder()

    .ConfigureFunctionsWorkerDefaults()

    .ConfigureServices(services =>
    {

        services.Configure<JsonSerializerOptions>(options =>
        {
            options.Converters.Add(new JsonStringEnumConverter());
            options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; // Ignore null values during serialization
        });
       
        services.AddApplicationInsightsTelemetryWorkerService();
        services.ConfigureFunctionsApplicationInsights();
       

    })
    .ConfigureAppConfiguration((context, config) =>
    {
        config.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true);
        config.AddEnvironmentVariables();
    })

    .Build();


host.Run();

Example Function

namespace serviceBus.QueueTrigger
{
    public class ServiceBusQueueTrigger
    {
        private readonly ILogger<ServiceBusQueueTrigger> logger;
        public ServiceBusQueueTrigger(ILoggerFactory loggerFactory)
        {
            logger = loggerFactory.CreateLogger<ServiceBusQueueTrigger>();
        }
       
        [Function(nameof(ServiceBusQueueTrigger))]
        public async Task Run(
            [ServiceBusTrigger("baseloadqueue", Connection = "serviceBusConnectionString")]
            ServiceBusReceivedMessage message,
            ServiceBusMessageActions messageActions)
        {
          
            logger.LogInformation("queue triggered");
        }
    }
}

I expecting the any solution to get the log file for my function app now im trying to export thte app insight to get the log file is any other way to get the log file for our project is also okay for me.


Solution

  • Add the Telemetry logging configuration in your Program.cs.

    Use below modified code to log the ILogger messages to Application insights.

    Program.cs:

    var host = new HostBuilder()
        .ConfigureFunctionsWebApplication()
        .ConfigureServices((context, config_services) =>
        {
            IConfiguration config = context.Configuration;
            config_services.AddLogging(loggingBuilder =>
            {
                var con_strg = config["kpconnstring"];
                var kplogconfig = new LoggerConfiguration()
                    .MinimumLevel.Information()
                    .Enrich.FromLogContext();
                kplogconfig.WriteTo.ApplicationInsights(con_strg, TelemetryConverter.Traces);
                loggingBuilder.AddSerilog(kplogconfig.CreateLogger());
            });
            config_services.AddApplicationInsightsTelemetryWorkerService();
            config_services.ConfigureFunctionsApplicationInsights();
        })
        .ConfigureAppConfiguration((context, configBuilder) =>
        {
            configBuilder.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true);
        })
        .Build();
    host.Run();
    

    host.json:

    {
      "version": "2.0",
      "logging": {
        "fileLoggingMode": "always",
        "logLevel": {
          "default": "Information"
        },
        "applicationInsights": {
          "samplingSettings": {
            "isEnabled": false,
            "excludedTypes": "Request"
          },
          "enableLiveMetricsFilters": true
        }
      }
    }
    

    local.settings.json:

    {
      "IsEncrypted": false,
      "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
        "SBconnection": "<Service_Bus_connection_string>",
        "kpconnstring": "<Application_insights_connection_string>"
      }
    }
    

    Function code:

    private readonly ILogger<Function1> _logger;
    
    public Function1(ILogger<Function1> logger)
    {
        _logger = logger;
    }
    
    [Function(nameof(Function1))]
    public async Task Run(
        [ServiceBusTrigger("queue1", Connection = "demo")]
        ServiceBusReceivedMessage message,
        ServiceBusMessageActions messageActions)
    {
        _logger.LogInformation("Message ID: {id}", message.MessageId);
        _logger.LogInformation("Message Body: {body}", message.Body);
        _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
        await messageActions.CompleteMessageAsync(message);
    }
    

    The Ilogger logs will be stored as Traces in application insights.

    union isfuzzy=true
        availabilityResults,
        requests,
        exceptions,
        pageViews,
        traces,
        customEvents,
        dependencies
    | where timestamp > datetime("2024-07-21T10:52:11.299Z") and timestamp < datetime("2024-07-22T10:52:11.299Z")
    | order by timestamp desc
    | take 100
    

    enter image description here

    enter image description here