How to implement logging in blazor
I’m using Blazor (3.1) Server approach
I want to log (to a file) some events
I have try this extension: https://github.com/BlazorExtensions/Logging but I can’t make it to work as it says.
Can someone point me to a working example? Or Tell me if I’m doing something wrong (I’m getting this error with this approach:
A circular dependency was detected for the service of type 'Microsoft.JSInterop.IJSRuntime)
In order to implement logging for Blazor server you would follow the same approach as you would for a .NET Core or ASP.NET Core application.
Namely in your Program.cs file you would need to modify the CreateHostBuilder method to configure your loggers in a manner such as
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
You could then inject an ILogger into your razor components or throughout the rest of your application using dependency injection.
public class AboutModel : PageModel
{
private readonly ILogger _logger;
public AboutModel(ILogger<AboutModel> logger)
{
_logger = logger;
}
public string Message { get; set; }
public void OnGet()
{
Message = $"About page visited at {DateTime.UtcNow.ToLongTimeString()}";
_logger.LogInformation(Message);
}
}
Be sure to check the Microsoft documentation for information on built in loggers, third party loggers, and just logging in general.
you can use Serilog
this implementation for server side https://www.c-sharpcorner.com/article/log-data-into-file-using-serilog-framework-in-blazor-server-app/
and this for client side https://nblumhardt.com/2019/11/serilog-blazor/
also you will need to read https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-5.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With