代码改变世界

serilog 动态更新日志级别

  qgbo  阅读(368)  评论(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.

 

相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示