Search code examples
asp.net-coreblazor-server-sideilogger

How can I get an ILogger in an exception handler - created in Main()?


Blazor Interactive Server - in Program.cs, at the of Main() I have the following exception handlers

    AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
    {
        var exception = eventArgs.ExceptionObject as Exception;
        Console.Error.WriteLine($"Unhandled exception: {exception?.Message}");
    };
    TaskScheduler.UnobservedTaskException += (sender, eventArgs) =>
    {
        var exception = eventArgs.Exception;
        Console.Error.WriteLine($"Unobserved task exception: {exception?.Message}");
    };

    logger.LogInformation("***** Initialization complete.");
    await app.RunAsync();
}

I would like to use a 'logger' object to log these. I've tried to test hitting these but I can't come up with an exception that is not handled elsewhere. So any suggestions for that would be appreciated.

I assume the logger object in scope when these are create cannot be used in the anonymous methods declared here because it will be out of scope once Main() returns. Is there any way to create an ILogger object in these methods?

And if not, is there a call that will write a string to the logs as I assume a write to Console does not go to the logs.


Solution

  • You Can Check Test Result First

    enter image description here

    enter image description here

    enter image description here

    enter image description here

    You can get an ILogger in an exception handler like below.

    using BlazorApp2.Components;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    builder.Services.AddRazorComponents()
        .AddInteractiveServerComponents();
    
    var app = builder.Build();
    
    
    
    //******************************* Test From Here <START>*******************************
    var loggerFactory = app.Services.GetRequiredService<ILoggerFactory>();
    
    // Attach the exception handlers
    AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
    {
        var logger = loggerFactory.CreateLogger("GlobalExceptionHandler");
        var exception = eventArgs.ExceptionObject as Exception;
        logger.LogError(exception, "Unhandled exception occurred.");
    };
    
    TaskScheduler.UnobservedTaskException += (sender, eventArgs) =>
    {
        var logger = loggerFactory.CreateLogger("GlobalTaskExceptionHandler");
        logger.LogError(eventArgs.Exception, "Unobserved task exception occurred.");
    };
    
    var logger = loggerFactory.CreateLogger<Program>();
    logger.LogInformation("***** Initialization complete.");
    
    //*******************************      Test <END>       *******************************
    
    
    
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error", createScopeForErrors: true);
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    
    app.UseStaticFiles();
    app.UseAntiforgery();
    
    app.MapRazorComponents<App>()
        .AddInteractiveServerRenderMode();
    
    app.Run();