代码改变世界

serilog 动态更新日志级别

2022-11-10 18:11  qgbo  阅读(277)  评论(0编辑  收藏  举报

使用这个库,更新配置文件,就可以动态更新 日志输出级别。

new LoggerConfiguration().ReadFrom.Configuration(hostingContext.Configuration)

这个Configuration 定义在这儿

return settingConfiguration.Settings(
                new ConfigurationReader(
                    configuration.GetSection(sectionName),
                    assemblyFinder,
                    configuration));

进到这个 reader 里面,有 实现接口的方法:这个 Configure method 会在 上面的方法直接调用。

 1 public void Configure(LoggerConfiguration loggerConfiguration)
 2         {
 3             ProcessLevelSwitchDeclarations();
 4             ProcessFilterSwitchDeclarations();
 5 
 6             ApplyMinimumLevel(loggerConfiguration);
 7             ApplyEnrichment(loggerConfiguration);
 8             ApplyFilters(loggerConfiguration);
 9             ApplyDestructuring(loggerConfiguration);
10             ApplySinks(loggerConfiguration);
11             ApplyAuditSinks(loggerConfiguration);
12         }

其中有ApplyMinimumLevel, 这是设置日志级别的地方:

这下面会调用 ChangeToken.OnChange... 

that is when IConfiguration changed, a delegate will be trigger.

and this will change the LoggerConfiguration's MinimumLevel.ControlledBy(levelSwitch)

so below code also can change the level dynamicly:

public static LoggingLevelSwitch loggingLevelSwitch = new LoggingLevelSwitch();
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureLogging((hostingContext, loggingBuilder) =>
                {

                    Log.Logger = new LoggerConfiguration()
                        .MinimumLevel.ControlledBy(loggingLevelSwitch)
                        .WriteTo.Console()
                        .CreateBootstrapLogger();
                    
                    loggingBuilder.ClearProviders();
                    loggingBuilder.AddSerilog();
                })
                .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });

we can change the level at any time without the application restarting.