Logging to a file in Blazor WASM

Viewed 2428

I am new to Blazor. I want to log to a file in client side of Blazor WASM. I tried using serilog and serilog.sink.file. But I don't see any logs written to a file. I also don'see any errors. Is it because Blazor WASM operates in the browser sandbox which cannot access local filesystem.Is there any way to log to file from Blazor WASM.

The code I tried for configuring in Main:

Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Is(logLevel)
            .WriteTo.File(path: @"C:\Users\abc\logs.log",
                          rollingInterval: RollingInterval.Day,
                          rollOnFileSizeLimit: true,
                          fileSizeLimitBytes: 10 * 1024 * 1024)                
            .CreateLogger();
 Log.Information("testing");
2 Answers

There is no way to log blazor WASM in file directly. Because codes fully run in browser. You also can use other serilog sinks like browserconsole or blazor relay that provide special for blazor

If you want to write your log to a file on the client you can log to console then launch chrome with an option to redirect logs:

--enable-logging=stderr --v=1 > log.txt 2>&1

It's easier to log to console and use F12 in your browser to view the logs. I use Microsoft.Logging.Extensions:

https://www.nuget.org/packages/Microsoft.Extensions.Logging

Then I configure in Program.cs with:

            builder.Services.AddLogging(builder => builder
                .SetMinimumLevel(LogLevel.Debug)
                .AddFilter("Microsoft", LogLevel.Warning)
                .AddFilter("System", LogLevel.Warning)
            );

Then I inject and call the logger with:

        [Inject] protected ILogger<MyClassIamLoggingFrom> Logger { get; set; }

        Logger?.LogDebug("Fetching install data");
Related