Serilog自定义Enricher分组:如何仅在appsettings.json配置组名
解决方案:将Serilog自定义Enricher分组,通过配置文件组名批量注册
步骤1:扩展批量添加Enricher的组方法
在现有LoggingExtensions类中,新增一个扩展方法,一次性打包所有需要分组的自定义Enricher:
public static class LoggingExtensions { // 保留原有的单个Enricher扩展方法 public static LoggerConfiguration WithAddDateTimeNow( this LoggerEnrichmentConfiguration enrich) { if (enrich == null) throw new ArgumentNullException(nameof(enrich)); return enrich.With<AddDateTimeNowEnricher>(); } public static LoggerConfiguration WithUserName( this LoggerEnrichmentConfiguration enrich) { if (enrich == null) throw new ArgumentNullException(nameof(enrich)); return enrich.With<UserNameEnricher>(); } // 新增:批量添加组内所有Enricher的方法 public static LoggerConfiguration WithCustomEnrichersGroup( this LoggerEnrichmentConfiguration enrich) { if (enrich == null) throw new ArgumentNullException(nameof(enrich)); return enrich .With<UserNameEnricher>() .With<AddDateTimeNowEnricher>(); } }
步骤2:修改appsettings.json配置
在Serilog配置的enrich节点中,直接通过组名(去掉扩展方法的With前缀)批量注册:
{ "Serilog": { "MinimumLevel": "Information", "Enrich": [ "CustomEnrichersGroup" // 仅需填写组名,无需逐个列出Enricher ], "WriteTo": [ { "Name": "Console" } ] } }
步骤3:确保配置加载时识别扩展方法
在程序启动初始化Serilog时,保证LoggingExtensions所在程序集被加载即可,ASP.NET Core项目的典型初始化代码如下:
var builder = WebApplication.CreateBuilder(args); // 从配置文件加载Serilog配置 builder.Host.UseSerilog((context, configuration) => configuration.ReadFrom.Configuration(context.Configuration)); // 后续启动逻辑...
原理说明
Serilog配置系统会自动匹配Enrich数组中的名称与LoggerEnrichmentConfiguration的扩展方法(匹配规则为去掉方法名的With前缀)。通过创建批量添加的扩展方法,就能用一个组名替代多个单个Enricher的重复注册。
内容的提问来源于stack exchange,提问作者koyuboy
相关产品推荐
相关产品推荐

