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?
IExternalScopeProviderto 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 privateIExternalScopeProviderinjected 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.