Search code examples
asp.net-coreentity-framework-coreentity-framework-migrationsserilog

Migration Bundle Logs not being sent to Seq


When executing migration bundles logs are not sent to Seq. When executing the application normally everything is neatly sent to Seq.

First I assumed it was because Log.CloseAndFlush() was not called, because I had previously troubles with that, that's why I migrated to the minimal hosting model, now I get the last log "Stopped web application" but logs are still not sent to seq when running migration bundles.

Program.cs:

// truncated ...

IConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
    .SetBasePath(directoryName)
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false);

if (!string.IsNullOrWhiteSpace(environment))
{
    configurationBuilder.AddJsonFile($"appsettings.{environment}.json", optional: false, reloadOnChange: false);
}

configurationBuilder.AddEnvironmentVariables()
    .AddEnvironmentVariables(EnvPrefix);

Log.Logger = new LoggerConfiguration().ReadFrom
    .Configuration(configurationBuilder.Build())
    .CreateLogger();

Console.WriteLine("Created bootstrapping logger");

try
{
    Log.Information("Bootstrapping web application");

    WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

    builder.Services.AddSerilog(logger => logger.ReadFrom.Configuration(builder.Configuration));

    builder.Services.AddControllersWithViews();

    builder.Services.AddDbContext<SomeDbContext>(
        options => options.UseNpgsql(builder.Configuration.GetConnectionString("db")!,
        options => options.MigrationsAssembly(typeof(SomeDbContext).GetTypeInfo().Assembly.GetName().Name))
    );

    // truncated ...

    Log.Information("Building web application");

    WebApplication app = builder.Build();
    app.UseSerilogRequestLogging();

    // truncated ...

    Log.Information("Starting web application");

    app.Run();
}
catch (Exception exception)
{
    // https://github.com/dotnet/runtime/issues/60600
    if (exception.GetType().Name.Equals("StopTheHostException", StringComparison.Ordinal))
    {
        throw;
    }

    Log.Fatal(exception, "Unhandled exception was caught: {Message}", exception.Message);
}
finally
{
    Log.Information("Stopped web application");

    Log.CloseAndFlush();
}

appsettings.json:

{
    "Serilog": {
        "Using": [
            "Serilog.Sinks.Console",
            "Serilog.Sinks.Seq",
            "Serilog.Enrichers.ClientInfo"
        ],
        "MinimumLevel": {
            "Default": "Information"
        },
        "Enrich": [
            {"Name": "FromLogContext"},
            {"Name": "WithCorrelationId", "Args": {"headerName": "x-correlation-id", "addValueIfHeaderAbsence": true}}
        ],
        "Properties": {
            "Application": "app-name"
        },
        "WriteTo": [
            {"Name": "Console"},
            {"Name": "Seq", "Args": {"serverUrl": "http://your-seq-url"}}
        ]
    }
    // truncated ...
}

At this point I have no Idea why the logs might not be sent to Seq and I am on the brink of scrapping migration bundles. This only happens using efc migration bundles, everything works fine when running normally.


Solution

  • I found a workaround. When using migration bundles just adapt your appsettings*.json to use AuditTo instead of WriteTo and then the logs will be sent without needing to call Log.CloseAndFlush()

    {
        "Serilog": {
        // truncated ...
            "AuditTo": [
                {"Name": "Console"},
                {"Name": "Seq", "Args": {"serverUrl": "http://your-seq-url"}}
            ]
        }
        // truncated ...
    }
    
    

    Note: Keep in mind using this during normal application run will have performance problems.