BkLoggingProvider

Learn how to use BkLoggingProvider

BkLoggingProvider

BkLoggingProvider is a built-in logging solution provided by the BlazorForKids framework. It allows you to automatically store application logs in a SQL Server database. Logging is an essential feature when building any application because it helps you:

  • Understand what the application is doing behind the scenes
  • Identify and fix bugs faster
  • Track user behavior and events
  • Debug production issues using historical data

However, using the BkLoggingProvider is not mandatory. You are free to use any logging provider you prefer (such as Serilog, NLog, or built-in file logging). This feature exists to make it easy for developers, especially beginners, to get started with logging quickly—no extra setup or packages needed.

How to Enable BkLoggingProvider

To activate BkLoggingProvider, you only need to change one option during application setup. Go to your Program.cs file and update the BlazorForKids configuration like this:

Step 1: Enable BkLogger in Program.cs

builder.AddBlazorForKids<ApplicationDbContext>(options =>
{
    options.UseBkLoggerToDatabase = true;
    options.UseDefaultCachePipeline = true;
    options.HideUserRegistrationPage = true;
    options.AuthenticationType = BkAuthenticationType.BasicAuthentication;
    options.IdentityOptions = o =>
    {
        o.SignIn.RequireConfirmedAccount = false;
        o.Password.RequireDigit = true;
        o.Password.RequireLowercase = true;
        o.Password.RequireUppercase = true;
        o.Password.RequiredLength = 8;
        o.Password.RequireNonAlphanumeric = true;
    };
});

By setting UseBkLoggerToDatabase = true, you tell the framework to use the internal database logger.

Step 2: Add Logging Configuration to appsettings.json

Open your appsettings.json file and make sure you have the following configuration inside the "Logging" section:

"Logging": {
  "LogLevel": {
    "Default": "Information",
    "Microsoft.AspNetCore": "Warning",
    "Microsoft.EntityFrameworkCore": "None"
  },
  "BkLoggingDb": {
    "ConnectionString": "Server=.;Database=DevelopmentLogs;Trusted_Connection=True;MultipleActiveResultSets=true;Encrypt=False;TrustServerCertificate=True;Connection Timeout=30;",
    "TableName": "Logs_BlazorForKids",
    "MinimumLogLevel": "Information"
  }
}

ConnectionString: You can use one for development (local SQL Server), and a different one for production.

TableName: This is the name of the SQL table where logs will be stored.

MinimumLogLevel: Use this to control what kind of logs are saved. You can use values like Debug, Information, Warning, or Error.

Automatic Table Creation

After setup, the framework will automatically create the logs table in your database if it does not exist. The generated SQL command looks like this:

IF NOT EXISTS (
    SELECT * FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_NAME = 'Logs_BlazorForKids'
)
BEGIN
    CREATE TABLE [Logs_BlazorForKids] (
        [Id] INT IDENTITY(1,1) PRIMARY KEY,
        [Timestamp] DATETIME2(7) NOT NULL DEFAULT SYSUTCDATETIME(),
        [LogLevel] NVARCHAR(20) NOT NULL,
        [Category] NVARCHAR(256) NULL,
        [Message] NVARCHAR(MAX) NOT NULL,
        [Exception] NVARCHAR(MAX) NULL,
        [Parameters] NVARCHAR(MAX) NULL
    );

    CREATE NONCLUSTERED INDEX IX_Logs_BlazorForKids_Timestamp ON [Logs_BlazorForKids] ([Timestamp]);
    CREATE NONCLUSTERED INDEX IX_Logs_BlazorForKids_LogLevel ON [Logs_BlazorForKids] ([LogLevel]);
    CREATE NONCLUSTERED INDEX IX_Logs_BlazorForKids_Category ON [Logs_BlazorForKids] ([Category]);
END

You don't need to run any manual migrations or SQL scripts. The framework handles this automatically for you.

Controlling What Gets Logged

The type of logs that are stored depends on the value you set in MinimumLogLevel. For example:

  • Information: Saves all info, warnings, and errors
  • Warning: Saves only warnings and errors
  • Error: Only critical issues will be logged

This helps you control the amount of data stored, especially in production environments.

Final Notes

  • BkLoggingProvider is optional—you are free to use any logger you like.
  • If you activate it, the framework handles setup, table creation, and database writing automatically.
  • The logs are written in a structured format so you can analyze or export them easily.

With just a few lines of configuration, you can have a robust, database-backed logging system that helps you monitor, debug, and maintain your Blazor app more effectively.

Need more help? Check out the examples and video tutorials on the official BlazorForKids website.

Advanced Usage

Logging with Parameters

The BkLoggingProvider supports structured logging, which means you can attach key-value data (called parameters) to your log messages. This is useful when you want to log objects like input models, user actions, or other contextual data.

For example, in your service or controller:

_logger.LogInformation("User submitted the payment form {@PaymentInfo}", paymentModel);

This will log both the message and a serialized version of the paymentModel as JSON in the Parameters column. If the object cannot be serialized, its type name or fallback ToString() will be stored instead.

These parameters are extremely helpful when investigating an issue because you can see what data was involved in a certain action or exception.

Filtering Logs by LogLevel or Category

You can control how much information is logged using the MinimumLogLevel setting inside appsettings.json. Here's a breakdown of levels from most to least verbose:

  • Trace: Very detailed logs, mostly used for deep debugging
  • Debug: Useful information during development
  • Information: Standard application events (e.g., user logged in)
  • Warning: Something unexpected happened, but the app can continue
  • Error: An error occurred that might require developer attention
  • Critical: A major failure, likely crashing the app

Example config to reduce noise from framework logs:

"LogLevel": {
  "Default": "Information",
  "Microsoft": "Warning",
  "Microsoft.EntityFrameworkCore": "None"
}

Viewing Logs in SQL Server

All logs are stored in the table defined by "TableName" (e.g., Logs_BlazorForKids). You can open SQL Server Management Studio (SSMS) or any SQL client and run:

SELECT TOP 100 * FROM Logs_BlazorForKids ORDER BY Timestamp DESC;

To find all errors within a time range:

SELECT * 
FROM Logs_BlazorForKids 
WHERE LogLevel = 'Error' 
AND Timestamp BETWEEN '2025-04-01' AND '2025-04-20';

You can even filter by Category or keywords inside Message or Parameters.

Example: Query Logs by User Action

If you're logging events like this:

_logger.LogInformation("User {UserId} confirmed payment {@Payment}", userId, payment);

You can query the logs using SQL LIKE filters:

SELECT * 
FROM Logs_BlazorForKids 
WHERE Parameters LIKE '%"UserId":"123"%';

Or search for all logs related to a certain entity:

SELECT * 
FROM Logs_BlazorForKids 
WHERE Parameters LIKE '%"Payment"%';

Switching to Production Mode

When deploying to a production server, remember to change your logging configuration to avoid unnecessary noise:

  • Use a separate connection string for production
  • Increase the MinimumLogLevel to Warning or Error
"BkLoggingDb": {
  "ConnectionString": "Server=prod-server;Database=ProductionLogs;Trusted_Connection=True;",
  "TableName": "Logs_BlazorForKids",
  "MinimumLogLevel": "Warning"
}

Combining with Other Logging Providers

BlazorForKids does not force you to use its logger exclusively. You can combine it with other loggers like Serilog, file loggers, or third-party tools. Just configure them side by side in Program.cs or appsettings.json.

Tips for Effective Logging

  • Log only what is useful. Avoid flooding the log table with unnecessary debug messages.
  • Include context in your messages (e.g., user ID, action type, model name).
  • Use structured logging with parameters instead of plain text only.
  • Review logs regularly to detect patterns, errors, or potential improvements.

Logging: Do's and Don'ts

Before you start writing logs, it's important to understand what you should and shouldn't include in them. Here are some practical tips to help you use logging in a safe and responsible way:

✅ What You Should Do

  • Log meaningful events – such as user logins, data updates, exceptions, or validation errors.
  • Use structured logging – pass objects as parameters so they are saved in JSON format and easier to search.
  • Include context – add identifiers like user ID, order ID, or page name when relevant to understand the flow.
  • Control log levels – log detailed messages only during development, and reduce verbosity in production.
  • Use logs to help future-you – imagine you're debugging a problem 6 months from now. What info would you want to see?

❌ What You Should Avoid

  • Never log passwords – even encrypted. Just don’t log them.
  • Don’t log personal identifiable data (PII) like email addresses, phone numbers, or national IDs unless absolutely necessary—and only if properly secured.
  • Don’t over-log – avoid logging every small step (like "button clicked") unless you really need that level of detail.
  • Don’t log large objects – especially in loops or very frequent operations. This can slow down your app and flood the database.
  • Don’t forget the user’s privacy – if your app is used by real people, you have a responsibility to respect their data.

✅ A good rule of thumb: If you wouldn’t feel comfortable seeing a piece of data in a public screenshot, don’t log it!

Logging is one of the most powerful tools in software development—but like any tool, it should be used wisely.

Need Help?

If you're unsure how to use structured logging, configure log levels, or view your logs, check out the tutorials and video guides on the BlazorForKids official site.

Logging may sound technical at first, but once you start using it, it becomes one of the most powerful tools in your toolbox as a developer.


© BlazorForKids Framework – Simplifying software development for all ages

An unhandled error has occurred. Reload 🗙