Logging in Blazor

It’s not unusual for us to need to output log message to file, console etc. Obviously there’s going to be a different in capabilities for logging from WASM (essentially on the client browser) and on a server.

Blazor supplies the logging framework

Blazor supplies loggin via the ILogger, ILogger, ILoggerFactory and ILoggerProvider interfaces. In most cases you’ll use the ILogger and ILogger.

Logging capabilities are supplied via the WebAssemblyHostBuilder on WebAssembly and Host on the server (see Program.cs in both project types).

We can therefore use these interfaces/implementation via injection like this

@inject ILogger Logger;
// OR
@inject ILogger<MyPage> Logger;

Alternatively we might use the ILogFactory like this

@inject ILoggerFactory LoggerFactory

// with the following
var logger = LoggerFactory.CreateLogger<MyPage>();

Logging in WebAssembly

With WebAssembly on the client, we’d obviously expect to be logging to the Browser devtools. Whilst we can actually just use

Console.WriteLine("Message 1");
Debug.WriteLine("Message 2");

the Logging framework offers some extra functionality, such as categorisation of logs etc. To use the ILogger or ILogger, we simply use

Logger.LogWarning("Log a warning");

(we have the ability to log debug, warning, info etc.)

Logging to Server

For Blazor Server, the output from the logging will be visible in the console window if running as a standalone application or the output window of Visual Studio.

However if you want your Blazor server application to output to the browser, then you need to use the IJSRuntime, which we can inject like this

@inject IJSRuntime JsRuntime

and then use the runtime like this

JsRuntime.InvokeAsync<string>("console.log", "Browser Message");

as you can see, the runtime allows us access to the JavaScript runtime hosting our pages and we can call the console.log JavaScript method, passing the parameters for the method call. In our case it’s just a string “Browser Message”.

Adding custom logger

To add a custom logger we can use something like this, where the DebugProvider is our implementation of an ILoggingProvider

builder.Logging.AddProvider(new DebugProvider());

Configuration

Configuration is placed in the appsettings.json file (remember if you’re using appsettings.json on WebAssembly client then this should be placed in the wwwroot folder otherwise it’s not set to the browser). For server the appsettings.json can be in the project folder.

Here’s the template generated appsettings section for logging

"Logging": {
  "LogLevel": {
    "Default": "Trace",
    "Microsoft": "Warning",
    "Microsoft.Hosting.Lifetime": "Information"
  }
},