Azure function apps, logging in program.cs

Charlie Curtis 0 Reputation points
2026-11-21T13:25:03.5966667+00:00

Is it possible to capture logs in application insights (or somewhere else) during the setup phrase in program.cs?

Would like to be able to get checks that configuration elements are correct, etc.

E.g.

......

console.writeline("KV successfully accessed...");

....

Builder.build.run();

(.net 10, flex consumption)

Azure Functions
Azure Functions

An Azure service that provides an event-driven serverless compute platform.

0 comments No comments

1 answer

Sort by: Most helpful
  1. Marcin Policht 113.9K Reputation points MVP Volunteer Moderator
    2026-11-21T14:07:55.1333333+00:00

    yep - you can use ILogger after builder.Build() and before app.Run(). This allows startup checks to write to Application Insights, assuming its logging configuration is in place.

    using Microsoft.Extensions.Logging;
    
    var builder = FunctionsApplication.CreateBuilder(args);
    
    builder.ConfigureFunctionsWebApplication();
    
    builder.Services.AddApplicationInsightsTelemetryWorkerService();
    builder.Services.ConfigureFunctionsApplicationInsights();
    
    // Register services
    
    var app = builder.Build();
    
    var logger = app.Services.GetRequiredService<ILogger<Program>>();
    
    logger.LogInformation("Starting configuration validation.");
    
    try
    {
        var keyVaultUri = builder.Configuration["KeyVaultUri"];
    
        if (string.IsNullOrWhiteSpace(keyVaultUri))
        {
            throw new InvalidOperationException(
                "KeyVaultUri configuration is missing.");
        }
    
        logger.LogInformation("Key Vault configuration is present.");
    
        // Perform actual Key Vault access validation here
    
        logger.LogInformation("Key Vault successfully accessed.");
    
        logger.LogInformation("Startup validation completed.");
    }
    catch (Exception ex)
    {
        logger.LogCritical(ex, "Startup validation failed.");
        throw;
    }
    
    app.Run();
    

    ILogger is preferable to Console.WriteLine() because it supports structured logging and can be routed to Application Insights.


    If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.

    hth

    Marcin

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.