© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
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)
{
}
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();
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
sub
) everytime in every log (or the tenant)
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

AspNetCore Null Exception
C#CC# / help
2y ago
❔ AspNetCore.Components.NavigationException
C#CC# / help
3y ago
❔ Aspnetcore Identity Override
C#CC# / help
3y ago
Custom Logger
C#CC# / help
15mo ago