Reading state values from a ILogger Scope

Viewed 1018

Is there a way to read/grab 'current scope' values? For example, I've added some 'global context' values in an IPageFilter:

// OnPageHandlerExecuting
var contextScopeValues = new Dictionary<string, object>
{
    { "UserId", "user-id-value" }
};
contextScope = logger.BeginScope( contextScopeValues );

// OnPageHandlerExecuted
contextScope?.Dispose();

If I call logger.LogInformation( "Doing something for {UserId}" ); during any of the page processing, this works and the message is rendered with proper UserId.

However, when using LoggerMessage, it throws a parse error if you don't have a string parameter.

public static class LoggerMessages
{
    private static readonly Action<ILogger> sampleActivity;

    static LoggerMessages()
    {
        // This line throw exception because a parameter was 'expected'
        sampleActivity = LoggerMessage.Define( "Start some activity for {UserId}" );
    }

    public static void SampleActivity( this ILogger logger ) => sampleActivity( logger, null );
}

Implemented correctly, it would look like this and pass in a string.

public static class LoggerMessages
{
    private static readonly Action<ILogger, string> sampleActivity;

    static LoggerMessages()
    {
        sampleActivity = LoggerMessage.Define<string>( "Start some activity for {UserId}" );
    }

    public static void SampleActivity( this ILogger logger, string userId ) => sampleActivity( logger, userId, null );
}

However, if I pass in a dummy value, it replaces the 'core context' value for all logging calls going forward. So I was hoping to be able to do something like logger.SampleActivity( logger.Scope[ "UserId" ] ); but it obviously does not exist. Do I have any options to use LoggerMessage for performance and use the 'core' UserId property?

0 Answers
Related