Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net core log Startup errors to app insights

I'm trying to log any startup errors but the logs are not flowing into application insights. I tried configuring app insights in program.cs but still I don't see any logs.

public static IHostBuilder CreateHostBuilder(string[] args) =>

    Host.CreateDefaultBuilder(args)
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.AddApplicationInsights();
            logging.SetMinimumLevel(LogLevel.Information);
        });
like image 832
ThejaSingireddy Avatar asked Oct 16 '25 03:10

ThejaSingireddy


1 Answers

By default it is not supported to handle exceptions from application startup, see this link.

What I did to get the logs into the application insights is to add a try/catch block in the Main of Program.cs and initialize the TelemetryClient manually.

See the following code:

    public static void Main(string[] args)
    {
        try 
        {
            CreateHostBuilder(args)
                .Build().Run();
        }
        catch(Exception ex) 
        {
            TelemetryConfiguration telemetryConfiguration = TelemetryConfiguration.CreateDefault();
            telemetryConfiguration.ConnectionString = "application-insights-connection-string";
            var telemetryClient = new TelemetryClient(telemetryConfiguration);
            telemetryClient.TrackException(ex);
            telemetryClient.Flush();
            throw;
        }
    }
like image 87
Roesmi Avatar answered Oct 17 '25 18:10

Roesmi