Home
/
Blogs
/
How to add logging to a Blazor WASM (client side web assembly application)

How to add logging to a Blazor WASM (client side web assembly application)

July 11, 2024, Abdush Miah

Summary

In this tutorial we delve into instruction on how you can add logging to your blazor client side web assembly application.

Step 1

Add the following nuget package to your application:

Microsoft.Extensions.Logging.Configuration

Step 2

Add the following custom logger configuration in your appsettings.json file:

"Logging":{
    "LogLevel":{
        "Default": "Information"
    }
}

Step 3

In your program.cs file add the following:

builder.Logging.AddConfiguration(builder.Configuration.GetSection("Logging"));

Step 4

Next in your .razor file add this to the top of your file in which you'd like log information:

@inject ILogger<MyComponent> Logger;

Step 5

Now in either your code behind file and or your @code{} block you can do the following to start logging

public string SomeMethod(){
    try{
        // some cool stuff happening here

        Logger.LogInformation("Just some information to log"); /** Logs information as it all went well **/
    }catch(Exceptopm ex){
        Logger.LogError($"Some important error which could help troubleshoot, details of the exception {ex}"); /** Logs error as something terrible happened **/
    }
}

References

https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/logging?view=aspnetcore-8.0