简体   繁体   中英

How to configure LogLevel in manually-created logger (dotnet core 3.1)

I want to manually create a logger that always log everything, down to the Trace level, without respect to configuration files. I'm attempting to do this by supplying my own configuration (via InMemoryConfiguration) when creating the logger. The code is below. (My goal is to inject a logger into the base class that accumulates log messages in an in-memory structure for examination by the descendant class).

My logger is created and works correctly (accruing messages), but both it and the console logger I also add see only Information level and above messages.

How can I modify this code so that the loggers I'm creating are called for all log events regardless of the LogLevel?

    using BaseLibrary;
    
    namespace BaseTestingLibrary
    {
        public class BaseClaseExposed : BaseLibrary.BaseLibraryClass
        {
    
            protected override void ConfigureLogger()
            {
    
                var loggingConfiguration = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("Logging:LogLevel:Default", "Trace"),
                    new KeyValuePair<string, string>("Logging:LogLevel:BaseTestingLibrary", "Trace")
                };
    
                var config = new ConfigurationBuilder()
                    .AddInMemoryCollection(loggingConfiguration)
                    .Build();
    
                using (
                    var factory = LoggerFactory.Create(
                        builder =>
                        {
                            builder.AddConfiguration(config);
                            builder.AddConsole();
                            builder.AddAccrual(_accruedMessages);
                        }
                    )
                )
                {
                    _logger = factory.CreateLogger<BaseClassExposed>();
                }
            }
        }
    }

If your goal is just setting the LogLevel to a hard value you don't need to use IConfiguration .

You can simply use:

public void ConfigureLogger()
{
    using (var factory = LoggerFactory.Create(builder =>
    {
        builder.AddConsole();
        builder.AddAccrual(_accruedMessages)
        builder.SetMinimumLevel(LogLevel.Trace);
    }))
    {
        _logger = factory.CreateLogger<BaseClaseExposed>();
    }
}

Documentation

Working example .netfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM