C#C
C#2y ago
TeBeCo

AspNetCore - Logger - Global Scope

If anyone know how to Push a Global Scope/State via the startup of an App i'm all hear.
Trying to do the same as what Serilog Enricher does, which using serilog

the Msft.Ext.Logging Api allow "local" scope by using:
logger.BeginScope(ListOfKeyValuePair)
{
}

adding that to a Middleware would force multiple middleware at multiple place (like if you need value from before/after auth)
and it will also break BackgroundService

Currently i've found uggly code like that:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();


var providers = app.Services.GetService<IEnumerable<ILoggerProvider>>() ?? [];
foreach (var provider in providers)
{
    if (provider is ISupportExternalScope scopedProvider)
    {
        var scopes = new LoggerExternalScopeProvider();
        scopes.Push(new KeyValuePair<string, object>("MyPropertyName", "the value"));
        scopedProvider.SetScopeProvider(scopes);
    }
}

app.Run();

it's not super DI friendly and also it's computed at startup, while i'd want the value to be evaluated when the logs are latter emited
like logging the userId (claim sub) everytime in every log (or the tenant)
Was this page helpful?