如何通过配置中的属性(如ApplicationName)丰富Serilog日志?
如何在Serilog配置中添加ApplicationName日志增强项
当然可以啦!你完全可以通过配置结合少量代码(或者纯配置)的方式,把自定义的ApplicationName属性添加到Serilog的日志增强项中,下面给你两种常用的实现方式:
方式一:纯配置快速实现(固定应用名称)
如果你的应用名称是固定值,直接在Serilog的配置里通过WithProperty语法就能搞定,不需要额外写代码:
{ "Serilog": { "Using": [ "Serilog", "Serilog.Enrichers.Environment", "Serilog.Enrichers.Process" ], "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", // 直接添加ApplicationName属性,值为你的应用名称 "WithProperty:ApplicationName=MyAwesomeApplication" ], // 其他Serilog配置(比如WriteTo等) } }
这种方式的好处是简单直接,所有配置都在json文件里完成,适合应用名称不会动态变化的场景。
方式二:动态读取配置中的ApplicationName(更灵活)
如果你的ApplicationName是放在配置文件的其他节点(比如根节点),想要动态读取并添加到日志中,可以通过自定义日志增强器实现:
第一步:在配置文件中定义ApplicationName和Serilog配置
{ "ApplicationName": "MyDynamicApp", "Serilog": { "Using": [ "Serilog", "Serilog.Enrichers.Environment", "Serilog.Enrichers.Process", "YourProjectAssemblyName" ], "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", // 引用我们自定义的增强器方法 "WithApplicationName" ], // 其他Serilog配置 } }
第二步:编写自定义日志增强器
创建一个实现ILogEventEnricher的类,再添加对应的扩展方法让Serilog配置能识别:
using Serilog; using Serilog.Core; using Serilog.Events; public class ApplicationNameEnricher : ILogEventEnricher { private readonly string _applicationName; public ApplicationNameEnricher(string applicationName) { _applicationName = applicationName ?? throw new ArgumentNullException(nameof(applicationName)); } public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) { // 将ApplicationName添加到日志事件中 logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("ApplicationName", _applicationName)); } } // 扩展方法,让Serilog的配置能识别WithApplicationName public static class ApplicationNameEnricherExtensions { public static LoggerConfiguration WithApplicationName( this LoggerEnrichmentConfiguration enrichmentConfiguration, string applicationName) { return enrichmentConfiguration.With(new ApplicationNameEnricher(applicationName)); } }
第三步:初始化Serilog时读取配置并绑定增强器
在应用启动时,从配置文件读取ApplicationName,并传给自定义增强器:
var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(config) // 从配置中读取ApplicationName并添加增强器 .Enrich.WithApplicationName(config["ApplicationName"]) .CreateLogger();
这种方式的好处是可以灵活读取配置中的动态值,甚至可以从环境变量、命令行参数等其他配置源获取ApplicationName。
内容的提问来源于stack exchange,提问作者Paulo Morgado
相关产品推荐
相关产品推荐

