Set up logging with Blazor WebAssembly

Viewed 3616

I'm doing some experiments with Blazor and want to set up logging. I see that Blazor logs to Microsoft.Extensions.Logging out of the box and that the log messages go to the developer console inside the browser. That is a nice start.

Now I want to try and log messages to other destinations as well. It could be a cloud-service. I'm wondering where to set that up. In ASP.NET Core, you would set it up using the ConfigureLogging method in Program.cs. But this isn't available with Blazor:

public static IWebAssemblyHostBuilder CreateHostBuilder(string[] args) =>
    BlazorWebAssemblyHost.CreateDefaultBuilder()
        .UseBlazorStartup<Startup>()
        .ConfigureLogging(...); // <- compile error

As a fallback, I'm trying to set it up through ConfigureServices in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddLogging(builder => builder
        .AddMyLogger()
        .SetMinimumLevel(LogLevel.Information));
}

with AddMyLogger:

public static ILoggingBuilder AddMyLogger(this ILoggingBuilder builder)
{
    builder.Services.AddSingleton<ILoggerProvider, MyLoggerProvider>();
    return builder;
}

and MyLoggerProvider:

public class MyLoggerProvider : ILoggerProvider
{
    public ILogger CreateLogger(string categoryName)
    {
        return new MyLogger();
    }

    public void Dispose()
    {
    }
}

and MyLogger:

public class MyLogger : ILogger
{
    public MyLogger()
    {
    }

    public IDisposable BeginScope<TState>(TState state)
    {
        return null;
    }

    public bool IsEnabled(LogLevel logLevel)
    {
        return true;
    }

    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
    {
    }
}

The AddMyLogger-method is called but my logger is never created or receives any Log-calls.

Am I doing something wrong here or is logging with Blazor WebAssembly simply not ready yet?

1 Answers

I was trying something similar. In my case, the Log method in MyLogger gets called; however it fails at following line of code

using (var streamWriter = new StreamWriter(fullFilePath, true)) //Fails here 
{
    streamWriter.WriteLine(logRecord);
} 

When I put it in try catch block, I got the exception "Children could not be evaluated". While researching I came across following link. Steve Sanderson's response might make sense of the behavior

Reading local files #16156

BTW It's been a long time, please let me know the solution you came up with.

Related