Logging with Serilog in Blazor: Server vs WebAssembly
A beginner's guide to adding Serilog to Blazor applications. It covers file and console sinks for Blazor Server and the browser console or remote API approaches for Blazor WebAssembly. Useful for Blazor developers who need to choose a logging strategy that fits their hosting model.
Key points
- Add the Serilog.AspNetCore package to a Blazor Server project and register it with AddSerilog.
- Use RollingInterval.Day on the file sink to start a new log file each day.
- Load Serilog settings from appsettings.json to change log levels and sinks without recompiling.
- Do not reference Serilog.AspNetCore in a Blazor WebAssembly client; use Serilog with the BrowserConsole sink instead.
- For production logs from WebAssembly users, send messages to a server API or a service such as Seq.
This tutorial introduces Serilog for Blazor applications and shows how the setup differs between hosting models. On the Blazor Server side, the Serilog.AspNetCore package is registered through AddSerilog, with console and daily rolling file sinks. Configuration can also be moved to appsettings.json so log levels and sinks can change without recompiling. Components receive an ILogger<T> through injection and write messages from event handlers.
Blazor WebAssembly needs a different approach, because Serilog.AspNetCore depends on the ASP.NET Core shared runtime and cannot run in the browser. The article suggests two options: writing to the browser console with the Serilog.Sinks.BrowserConsole sink, which suits local debugging, or sending logs to a remote service such as Seq or an ASP.NET Core endpoint, which is needed to collect data from real users. Picking the right path early avoids rework when the app moves to production.
Real-world use
- Tracing user actions and errors in a Blazor Server app through daily rolling log files.
- Debugging a Blazor WebAssembly client locally by reading logs in the browser developer tools.
- Collecting client-side errors from production users and forwarding them to a central logging service.
Why it matters
The hosting model decides where logs can be written, so a WebAssembly app needs a remote logging path before it goes to production. Server-only Serilog packages cannot be added to the client project.