Logging
- Introduction
- Complete Example: Structured Log Check
- Writing Log Messages
- Channels
- Configuration
- Constructor Injection
- Testing
Introduction
To help you learn more about what's happening in your application, DotBlaze provides the Log facade, a Laravel-style front for .NET's standard ILogger. DotBlaze does not have its own logging system: every message goes through ASP.NET Core's logging, so it appears in the same place as the framework's own logs (the console, by default) and works with any logging provider, such as Serilog or OpenTelemetry.
Writing Log Messages
The Log facade has one method per log level:
Log.Debug("Cache warmed in {Ms} ms", elapsed);
Log.Info("User {Id} logged in", user.Id);
Log.Warning("Disk usage at {Percent}%", 91);
Log.Error("Payment {Id} was declined", payment.Id);
Log.Critical("Database is unreachable");They map to .NET's levels: Debug → LogLevel.Debug, Info → Information, Warning → Warning, Error → Error, Critical → Critical. Laravel's notice, alert, and emergency levels have no .NET equivalent and are not available.
Message Templates
Messages are .NET message templates, not interpolated strings. Pass values as arguments and name them with {Placeholders}:
Log.Info("Post {PostId} published by {UserId}", post.Id, user.Id);The rendered message is Post 12 published by 3, and structured logging providers also store PostId and UserId as separate fields, which plays the role of Laravel's context array. Avoid $"..." interpolation in log calls: it loses the structured fields.
Logging Exceptions
Error has an overload that takes the exception first:
try
{
await SendInvoice(invoice);
}
catch (Exception e)
{
Log.Error(e, "Failed to send invoice {Id}", invoice.Id);
}Unhandled exceptions in requests, jobs, and scheduled tasks are logged for you. To send them elsewhere as well, change their level, or leave some out, see Error Handling.
Channels
In Laravel, a channel decides where a message is written. In DotBlaze, a channel is a .NET logger category. The Log methods above write to the App category (available as the constant Log.DefaultChannel). Log.Channel(name) writes to another category and offers the same methods:
Log.Channel("payments").Warning("Refund {Id} needs review", refund.Id);
Log.Channel("slack").Critical("Disk full");A category does not choose a destination on its own: messages from every category go to every configured provider. Use categories to tell messages apart and to give parts of your application different log levels. Sending a category to a specific destination (for example Slack) is done with a logging provider that supports filtering by category.
Configuration
Log Levels
Log levels use ASP.NET Core's standard Logging configuration section. Since a config class's name becomes its key prefix and keys are case-insensitive, a LoggingConfig class in config/Logging.cs maps to that section. Category names with dots go in a dictionary:
public class LoggingConfig : ConfigFile
{
public override object Values() => new
{
LogLevel = new Dictionary<string, object>
{
["Default"] = "Information",
["Microsoft.AspNetCore"] = "Warning",
["App"] = "Debug",
["payments"] = "Warning",
},
};
}Default applies to every category without its own entry. Here, the default channel (App) logs everything from Debug up, the payments channel only Warning and above, and ASP.NET Core's own request logging is reduced to warnings.
The same settings can come from an appsettings.json file or from environment variables, which override the file:
export Logging__LogLevel__Default=Warning
export Logging__LogLevel__App=DebugNOTE
Without any Logging configuration, .NET logs Information and above for every category.
Log Providers
A DotBlaze application uses ASP.NET Core's default logging providers: the console, the debug output, and EventSource (plus the Windows Event Log on Windows). To add or replace providers, configure logging in a service provider:
public class AppServiceProvider : Provider
{
public override void Register(IServiceCollection services, IConfiguration config)
{
services.AddLogging(logging =>
{
logging.ClearProviders();
logging.AddJsonConsole();
});
}
}Third-party providers such as Serilog are added the same way, with their own extension methods.
NOTE
DotBlaze does not include file, Slack, or other Laravel-style channel drivers. Use an ASP.NET Core logging provider for those destinations.
Constructor Injection
Because the Log facade is built on ILogger, you can inject a logger instead, the usual .NET way. The category is then the class name:
public class InvoiceService(ILogger<InvoiceService> logger)
{
public void Send(Invoice invoice) =>
logger.LogInformation("Sending invoice {Id}", invoice.Id);
}Testing
Log.Fake() replaces the logger with a recorder for the current test and returns it. Every message is recorded, whatever its level:
[Fact]
public void Logs_the_failed_invoice()
{
var log = Log.Fake();
Log.Info("User {Id} login", 7);
Log.Error(new InvalidOperationException("x"), "Failed to send invoice {Id}", 9);
Log.Channel("slack").Critical("Disk full");
log.AssertLogged(e => e is { Level: LogLevel.Information, Message: "User 7 login", Channel: Log.DefaultChannel });
log.AssertLogged(e => e.Level == LogLevel.Error && e.Exception is InvalidOperationException);
log.AssertLogged(e => e is { Channel: "slack", Level: LogLevel.Critical });
}Each recorded LogEntry has a Channel, a Level, the rendered Message, the Exception (or null), and a Context metadata snapshot. The fake offers:
AssertLogged(predicate): fails, listing the recorded messages, when no entry matches.AssertNothingLogged(): fails when anything was logged.Entries: all recorded entries, for your own assertions.
The fake only captures messages written through the Log facade, not through injected ILogger<T> instances. Call Log.Fake() directly in the test method; see Facades.
Complete Example: Structured Log Check
Create this file in the Blog template:
// app/Commands/LogDemo.cs
using DotBlaze;
using Microsoft.Extensions.Logging;
namespace Blog.Commands;
public class LogDemo : Command
{
public override string Signature => "demo:log";
public override Task<int> Handle()
{
var log = Log.Fake();
Context.Add("operation", "documentation");
Log.Info("Processed document {Id}", 42);
log.AssertLogged(entry =>
entry.Level == LogLevel.Information &&
entry.Message == "Processed document 42");
Line("Structured log recorded.");
return Task.FromResult(0);
}
}Run dotblaze demo:log. It prints the success line, while the application log is captured by the fake. Remove Log.Fake() and its assertion to send the structured event to configured logging providers. Use identifiers rather than request bodies or credentials in log properties.