Blazor WebAssembly – Changing The Log Level At Runtime

With Blazor WebAssembly we are now able to create single-page applications (SPA) using C# and the ASP.NET Core Framework. When coming from ASP.NET Core MVC, you may ask yourself what .NET features are available, limited, or not available when running in the browser. One of them is logging, which is a basic means for debugging in both production environments and during development.

In diesem Artikel:

Blazor WebAssembly – Changing The Log Level At Runtime
Pawel Gerr ist Architekt und Consultant bei Thinktecture. Er hat sich auf .NET Core Backends spezialisiert und kennt Entity Framework von vorne bis hinten.

Log levels in production

In this article, I will be looking back at my post about changing the log level from 2017. But this time, it will not be a full-featured platform like .NET Core 3.1 – but rather a browser with Blazor WebAssembly and .NET Standard code. The reason I use this feature is still the same as in 2017: By default, my applications usually have a log level of Information. If there is an issue in my code, I want to know the reason for it and then I need to lower the log level to get more information without rebuilding or restarting the application – in other words. reload the SPA. The main reason a reload of the app is undesirable is that the issue (which may be hard to reproduce) may just disappear.

Available log levels when using the Microsoft logging framework:

				
					public enum LogLevel
{
  Trace,
  Debug,
  Information,
  Warning,
  Error,
  Critical,
  None
}
				
			

Version information

.NET Core SDK: 3.1.302
ASP.NET Core Blazor WebAssembly: 3.2.1

The mentioned blog post from 2017 is addressing two logging frameworks, the Microsoft.Extensions.Logging and Serilog. This article here focuses on Microsoft.Extensions.Logging for simplicity reasons.

Demo application

To get started right away, I use the demo application that comes with the SDK. For that, we create a new Blazor WebAssembly project and make sure it works properly.

				
					dotnet new blazorwasm -o BlazorApp1
cd BlazorApp1
dotnet run
				
			

For the verification of the feature, we are going to implement a means to create a few logs. Let us put a new button on the page Index.razor which creates logs on a click.

				
					@page "/"

@using Microsoft.Extensions.Logging
@inject ILogger<Index> Logger

<button @onclick="CreateLogs">Create logs</button>

@functions {
    private void CreateLogs()
    {
        var logLevels = Enum.GetValues(typeof(LogLevel)).Cast<LogLevel>();

        foreach (var logLevel in logLevels.Where(l => l != LogLevel.None))
        {
            Logger.Log(logLevel, logLevel.ToString());
        }
    }
}
				
			

After starting the app and performing a click on the button, we should see some logs in the browser console.

There are 2 interesting points worth mentioning:

  • The WebAssemblyHostBuilder in Blazor WebAssembly registers a logging provider (WebAssemblyConsoleLoggerProvider) which logs onto the browser console
  • The default log level is Information (otherwise we would see the logs Debug and Trace)

Binding the log level to IConfiguration (a precondition for what comes next)

By default, there is no other way to change the log level besides hard-coding it using the WebAssemblyHostBuilder.

				
					// Program.cs

public static async Task Main(string[] args)
{
   var builder = WebAssemblyHostBuilder.CreateDefault(args);
   
   builder.Logging.SetMinimumLevel(LogLevel.Debug);
   ...
}

				
			

But we won’t do that. Instead, we bind the logger to the IConfiguration using the extension method AddConfiguration from the Nuget package Microsoft.Extensions.Logging.Configuration.

				
					// Program.cs

public static async Task Main(string[] args)
{
   var builder = WebAssemblyHostBuilder.CreateDefault(args);

   ConfigureLogging(builder);
   ...
}

private static void ConfigureLogging(
  WebAssemblyHostBuilder builder,
  string section = "Logging")
{
   builder.Logging.AddConfiguration(builder.Configuration.GetSection(section));
} 
				
			

To verify the results, we create a new file appsettings.json in the folder wwwroot, which changes the log level to Debug.

				
					{
    "Logging": {
        "LogLevel": {
            "Default": "Debug"
        }
    }
}
				
			

By switching the log level to Debug, we see our logs as well as the ones from Blazor.

Changing log level at runtime

For changing the log level at runtime, we need an implementation of a ConfigurationProvider that adds/changes the configuration values in memory. To save our customers (and me) some time, I made a few Nuget packages that provide the required components. In our demo we need Thinktecture.Extensions.Logging.Configuration which is made for Microsoft.Extensions.Logging.

Furthermore, we have to register the LoggingConfiguration with the current configuration builder and add it to the dependency injection (DI).

				
					private static void ConfigureLogging(
  WebAssemblyHostBuilder builder,
  string section = "Logging")
{
   var loggingConfig = new LoggingConfiguration();
   builder.Services.AddSingleton<ILoggingConfiguration>(loggingConfig);
   builder.Configuration.AddLoggingConfiguration(loggingConfig, section);

   builder.Logging.AddConfiguration(builder.Configuration.GetSection(section));
}
				
			

After adding the LoggingConfiguration to DI, we can inject it anywhere in the app using the interface ILoggingConfiguration.

Next, we create a UI component to be able to change the log level at runtime. For that, we create a new file LogLevelOverride.razor in the folder Shared with the following content.

				
					@using Thinktecture.Extensions.Configuration
@using Microsoft.Extensions.Logging

@inject ILoggingConfiguration Config
@inject ILogger<LogLevelOverride> Logger

<div>
    <label>
        Log Level override:
        <select @onchange="ChangeLogLevel">
            <option> - </option>

            @foreach (var logLevel in Enum.GetValues(typeof(LogLevel)))
            {
                <option value="@logLevel">@logLevel</option>
            }
        </select>
    </label>
</div>

@code{
    private void ChangeLogLevel(ChangeEventArgs obj)
    {
        if (Enum.TryParse(obj.Value?.ToString(), out LogLevel logLevel))
        {
            Config.SetLevel(logLevel);
        }
        else
        {
            Config.ResetLevel();
        }
    }
}
				
			

The last step is to finally add the component to the page Index.razor and to try it out.

				
					@page "/"

@using Microsoft.Extensions.Logging
@inject ILogger<Index> Logger

<LogLevelOverride />

<button @onclick="CreateLogs">Create logs</button>
...
				
			

Now we can set and reset (to default specified in appsettings.json) the log level at any time.

Summary

In this article, we saw how to change the log level of a Blazor WebAssembly application at runtime to get more (or less) information out of the application. A temporal change of the log level for debugging purposes is just one step in making the software development and maintenance easier. The next step could be a diagnostics page with more tools and statistics to get even more data out of the SPA.

Kostenloser
Newsletter

Aktuelle Artikel, Screencasts, Webinare und Interviews unserer Experten für Sie

Verpassen Sie keine Inhalte zu Angular, .NET Core, Blazor, Azure und Kubernetes und melden Sie sich zu unserem kostenlosen monatlichen Dev-Newsletter an.

Diese Artikel könnten Sie interessieren
Unterschiede
.NET
Blazor WebAssembly vs. Blazor Server – Welche Unterschiede gibt es und wann wähle ich was?

Blazor WebAssembly vs. Blazor Server – Welche Unterschiede gibt es und wann wähle ich was?

Das Blazor Framework von Microsoft gibt es inzwischen in drei "Geschmacksrichtungen". Die erste ist Blazor WebAssembly, die zweite Blazor Server, und zu guter Letzt gibt es noch Blazor Hybrid. In diesem Artikel wollen wir uns die zwei "echten", also Browser-basierten, Web-Anwendungs-Szenarien WebAssembly und Server anschauen.
04.07.2022
Three different textured walls
.NET
Dependency Injection Scopes in Blazor

Dependency Injection Scopes in Blazor

The dependency injection system is a big part of how modern ASP.NET Core works internally: It provides a flexible solution for developers to structure their projects, decouple their dependencies, and control the lifetimes of the components within an application. In Blazor - a new part of ASP.NET Core - however, the DI system feels a bit odd, and things seem to work a bit differently than expected. This article will explain why this is not only a feeling but indeed the case in the first place and how to handle the differences in order to not run into problems later on.
31.05.2022
.NET
Asynchrone Operationen: Blazor WebAssembly für Angular-Entwickler – Teil 5 [Screencast]

Asynchrone Operationen: Blazor WebAssembly für Angular-Entwickler – Teil 5 [Screencast]

Eine Webanwendung will natürlich auch mit Daten gefüttert werden. Doch diese müssen irgendwo her kommen. Nichts liegt näher als diese von einer Web API zu laden. Dieser Screencast zeigt, wie asynchrone Operationen in Blazor funktionieren und welche gravierenden Unterschiede es zu Angular gibt.
26.05.2022
.NET
Typings: Blazor WebAssembly für Angular-Entwickler – Teil 4 [Screencast]

Typings: Blazor WebAssembly für Angular-Entwickler – Teil 4 [Screencast]

C# und TypeScript entstammen der Feder der selben Person. Doch sind sie deshalb auch gleich? In diesem Teil der Screencast-Serie erfahren Sie, wie mit Typen in den beiden Programmiersprachen verfahren wird und welche Unterschiede es gibt.
19.05.2022
.NET
Bindings: Blazor WebAssembly für Angular-Entwickler – Teil 3 [Screencast]

Bindings: Blazor WebAssembly für Angular-Entwickler – Teil 3 [Screencast]

Wer Komponenten einsetzt, steht früher oder später vor der Fragestellung, wie man Daten an die Komponente übergibt oder auf Ereignisse einer Komponente reagiert. In diesem Screencast wird gezeigt wie Bindings bei Komponenten funktionieren, also wie eine Komponente Daten von außerhalb benutzen und Rückmeldung bei Aktionen geben kann.
12.05.2022
.NET
Komponenten: Blazor WebAssembly für Angular-Entwickler – Teil 2 [Screencast]

Komponenten: Blazor WebAssembly für Angular-Entwickler – Teil 2 [Screencast]

Bei der Entwicklung einer Webapplikation kommt es ständig vor, dass UI-Teile immer und immer wieder verwendet werden. Damit nicht immer Copy & Paste verwendet werden muss, können diese Teile in Komponenten zusammengefasst werden.
05.05.2022