6

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?

3
  • Hi @Terry,you can see this thread may helpful. Commented Jan 12, 2021 at 7:03
  • 1
    Thanks. I've actually read that already and that seemed more geared towards scopes lost due to exceptions, but doesn't talk about how to grab a scope property value that might have already been set. Unless I'm missing something. Commented Jan 12, 2021 at 18:55
  • 3
    @Terry looks like we use a so-called IExternalScopeProvider to get the scoped values (although not in a dictionary style). The scoped values are designed for custom logging provider to consume. Each provider has a private IExternalScopeProvider injected and you cannot access it from outside, unless you write your own custom provider like this meziantou.net/asp-net-core-json-logger.htm So there will not be an easy way for you to get and log out the scoped values using the built-in and third-party logging providers. Commented Jan 12, 2021 at 20:30

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.