Search code examples
asp.net-coreblazor-webassemblyserilog

Use serilog as logging provider in blazor webassembly client app


I'd like to use serilog in a blazor webassembly net 6 app, both on client and server sides. In this article I found out how to relay log entries to server so that they are written in log files.

In this approach however the Log static class is used to explicitly add log entries.

I'd like to add serilog as logging provider so that exceptions and automatically generated information are logged, too.

On server side I use

var builder = WebApplication.CreateBuilder(args);
builder.Host
    .UseSerilog((ctx, lc) =>
    {
        lc.ReadFrom.Configuration(ctx.Configuration);
    });

This way everything is passed to serilog.

UseSerilog is defined in Serilog.AspNetCore. Unfortunately, if I add Serilog.AspNetCore to my client project, the following error appears:

NETSDK1082 There was no runtime pack for Microsoft.AspNetCore.App available for the specified RuntimeIdentifier 'browser-wasm'

Is there a way to manually add serilog to logging providers, or in alternative, is there a way to add Serilog.AspNetCore package to client project?


Solution

  • I've been able to add Serilog to my client application logging providers by adding the Serilog.Extensions.Logging NuGet package.

    Then I used the following code:

    using Serilog;
    using Serilog.Core;
    using Serilog.Extensions.Logging;
    
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    
    /* ... */
    
    /* Serilog configuration
     * here I use BrowserHttp sink to send log entries to my Server app
     */
    var levelSwitch = new LoggingLevelSwitch();
    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.ControlledBy(levelSwitch)
        .Enrich.WithProperty("InstanceId", Guid.NewGuid().ToString("n"))
        .WriteTo.BrowserHttp(endpointUrl: $"{builder.HostEnvironment.BaseAddress}ingest", controlLevelSwitch: levelSwitch)
        .CreateLogger();
    
    /* this is used instead of .UseSerilog to add Serilog to providers */
    builder.Services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));