Blazor Logging - Tracking Application Events
Blazor Logging - Tracking Application Events
This demo will show how to use the built-in logging system in Blazor to record events and help with debugging and monitoring.
Concept: Imagine a security camera system in your house. It records specific events (someone opening a door, turning on a light, a potential issue) at different levels of detail, helping you understand what's happening.
Project Type: Blazor Server App (logging works similarly in WebAssembly, but server-side logs are easier to observe directly in the console/output window).
Step 1: Create the Blazor Server Project
- Open Visual Studio.
- Select "Create a new project".
- Choose "Blazor Server App" and click "Next".
- Name the project LoggingSimpleDemo.
- Click "Create".
Step 2: Configure Logging in Program.cs
This is where you tell Blazor where to send log messages and what level of detail to capture.
Open Program.cs in the root of your LoggingSimpleDemo project.
LoggingSimpleDemo/Program.cs (additions/modifications highlighted):
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; using LoggingSimpleDemo.Data; using Microsoft.Extensions.Logging; // Add this using statement for logging configuration var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddRazorPages(); builder.Services.AddServerSideBlazor(); builder.Services.AddSingleton<WeatherForecastService>(); // Configure Logging Providers and Filters: // Analogy: Setting up our security cameras and deciding what they should record. builder.Logging.ClearProviders(); // Clear default providers first to have full control builder.Logging.AddConsole(); // Send logs to the console window where the server runs builder.Logging.AddDebug(); // Send logs to the Debug output window in Visual Studio // Set minimum log levels for different categories (namespaces). // If a category isn't listed, it inherits from its parent or the Default. builder.Logging.SetMinimumLevel(LogLevel.Debug); // Default to Debug for everything if not specified builder.Logging.AddFilter("Microsoft", LogLevel.Warning); // Log only Warning and above for Microsoft-related components builder.Logging.AddFilter("System", LogLevel.Warning); // Log only Warning and above for System-related components // Log our custom components and services at Information level or higher. builder.Logging.AddFilter("LoggingSimpleDemo.Components.Pages.Counter", LogLevel.Information); // Our Counter page builder.Logging.AddFilter("LoggingSimpleDemo.Data.WeatherForecastService", LogLevel.Information); // Example existing service builder.Logging.AddFilter("LoggingSimpleDemo.Program", LogLevel.Information); // Messages from Program.cs itself var app = builder.Build(); // ... (rest of Program.cs remains unchanged) ...
Step 3: Client-Side: Inject and Use ILogger in a Blazor Component
We'll modify the default Counter.razor page to emit various types of log messages.
3.1. Modify Pages/Counter.razor:
Open Pages/Counter.razor.
LoggingSimpleDemo/Components/Pages/Counter.razor:
@page "/counter" @inject ILogger<Counter> Logger // Inject the ILogger specific to this Counter component <PageTitle>Counter</PageTitle> <h1>Counter with Logging</h1> <p role="status">Current count: @currentCount</p> <button class="btn btn-primary" @onclick="IncrementCount">Click me</button> @code { private int currentCount = 0; protected override void OnInitialized() { // Analogy: The camera records that the "Counter" component just started. Logger.LogInformation("Counter component initialized. Current count: {Count}", currentCount); } private void IncrementCount() { currentCount++; // Analogy: The camera records that the "Click me" button was pressed and the score changed. Logger.LogInformation("Counter incremented. New count: {Count}", currentCount); // Example of different log levels: if (currentCount % 5 == 0) { // Analogy: A warning - the score is getting high, might need attention soon. Logger.LogWarning("Counter reached {Count}! This is a multiple of 5.", currentCount); } if (currentCount % 10 == 0) { // Analogy: A critical event - the score hit a major milestone. Logger.LogCritical("!!! CRITICAL: Counter hit {Count} !!!", currentCount); } if (currentCount > 20 && currentCount % 2 != 0) { // Analogy: A debug message - very detailed, only recorded if debug mode is on. Logger.LogDebug("Counter is {Count} and odd. Just for internal debugging.", currentCount); } // Simulating a potential error (e.g., if a file wasn't found or an API call failed) if (currentCount == 13) // A "lucky" number for an error { try { throw new InvalidOperationException("Something bad happened at count 13!"); } catch (Exception ex) { // Analogy: An error - something went wrong, record the details to investigate. Logger.LogError(ex, "An error occurred when count was {Count}.", currentCount); } } } }
Step 4: Run the Demo and Observe
- Set
LoggingSimpleDemoas the startup project. - Run the application (
F5orCtrl+F5). - Navigate to the "Counter" page.
- Open the Output Window in Visual Studio: Go to
View > Output. In the "Show output from:" dropdown, select "Web Server" or "ASP.NET Core Web Server". - Click the "Click me" button repeatedly.
- Observe the Output Window:
- You'll see Information messages for each click.
- You'll see Warning messages every 5 clicks.
- You'll see Critical messages every 10 clicks.
- You'll see an Error message when the count hits 13, including the exception details.
- You'll see Debug messages only if
currentCountis odd and greater than 20 (and if the filter allows them, which it does asbuilder.Logging.SetMinimumLevel(LogLevel.Debug)is set).
Explanation of Concepts:
ILogger<T>Injection: This is the standard way to get a logger instance in your components and services. TheT(e.g.,Counter) helps categorize your logs, making them easier to filter and understand.- Log Levels: Blazor (and .NET) uses a standard set of log levels (Trace, Debug, Information, Warning, Error, Critical). You choose the appropriate level based on the severity and importance of the event.
- Logging Providers (
AddConsole(),AddDebug()): These configure where your log messages are sent. In a Blazor Server app, the Blazor components run on the server, so their logs appear in the server's console or debug output. - Log Filtering (
SetMinimumLevel(),AddFilter()): This allows you to control the verbosity of your logs. You can specify a minimum level for the entire application or for specific categories (namespaces). This is crucial in production to avoid overwhelming your logs with too much detail.
This tutorial guide clearly shows how to integrate and utilize the powerful logging capabilities in Blazor applications for monitoring and debugging.
Comments
Post a Comment