Reputation: 53
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");
Upvotes: 2
Views: 6298
Reputation: 642
This is all theoretical, but I see no reason why it wouldn't work...
If you want to log to a file to gain persistence for your log messages (maybe you are doing some troubleshooting?) then you could log to localStorage
. I use Blazored.LocalStorage
for this, making it very easy to do from C#.
Note that each entry in localStorage has a length limit, but it seems like in many modern browsers that limit is at least 5 MB. What is the max size of localStorage values?
So, first you would create your own custom logging provider that logs messages to a localStorage
entry. I would probably keep concatenating log messages to the same localStorage
entry, otherwise it would get out of hand fast.
https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/logging?view=aspnetcore-7.0
Then add your logger (in Program.cs for client-side Blazor), something like this:
builder.Services.AddSingleton<ILoggerProvider, CustomLoggerProvider>(services =>
{ return new CustomLoggerProvider(); });
Then inject and use as you would normally:
[Inject] ILoggerProvider loggerProvider { get; set; }
. . .
ILogger logger = loggerProvider.CreateLogger( GetType().FullName );
. . .
logger.LogInformation("Your message here");
Upvotes: 0
Reputation: 81
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");
Upvotes: 0
Reputation: 102
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
Upvotes: 3