.NET Framework Web应用能否从appsettings.json加载Serilog配置?
.NET Framework Web应用使用appsettings.json加载Serilog配置的解决方案
能否将配置代码放入Global.asax的Application_Start?
可以,但需要先解决程序集版本不匹配的问题,再调整配置细节才能正常运行。
程序集版本不匹配错误的解决方法
这个错误是因为项目中引用的Microsoft.Extensions.Configuration.Abstractions程序集版本与代码依赖的2.0.0.0版本不一致,按以下步骤处理:
- 打开NuGet包管理器,检查所有
Microsoft.Extensions.Configuration相关包(包括Abstractions、Json等)的版本,确保它们版本统一(建议选择稳定的2.x版本,比如2.2.0,避免跨版本依赖冲突)。 - 如果安装后仍有问题,在web.config中添加程序集绑定重定向,强制将旧版本重定向到当前安装的版本:
<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Microsoft.Extensions.Configuration.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-2.2.0.0" newVersion="2.2.0.0" /> </dependentAssembly> <!-- 其他相关配置包的绑定重定向,比如Microsoft.Extensions.Configuration.Json等 --> </assemblyBinding> </runtime>
调整Web应用中的配置代码
在Global.asax的Application_Start中,需要修改SetBasePath的路径(Web应用中Directory.GetCurrentDirectory()并非网站根目录),同时补充Build()方法调用:
using System.IO; using System.Web.Hosting; using Microsoft.Extensions.Configuration; using Serilog; protected void Application_Start() { var configuration = new ConfigurationBuilder() .SetBasePath(HostingEnvironment.ApplicationPhysicalPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .Build(); // 配置Serilog并引入请求头 enrichment Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(configuration) .Enrich.With(new RequestHeaderEnricher()) .CreateLogger(); // 后续初始化代码... }
实现请求头日志的自定义Enricher
要将请求头纳入日志,需实现Serilog的ILogEventEnricher接口:
using Serilog.Core; using Serilog.Events; using System.Web; public class RequestHeaderEnricher : ILogEventEnricher { public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) { var context = HttpContext.Current; if (context?.Request != null) { // 示例:添加指定请求头,比如User-Agent var userAgent = context.Request.Headers["User-Agent"]; if (!string.IsNullOrEmpty(userAgent)) { logEvent.AddOrUpdateProperty(propertyFactory.CreateProperty("UserAgent", userAgent)); } // 可选:添加所有请求头 foreach (string headerName in context.Request.Headers) { logEvent.AddOrUpdateProperty(propertyFactory.CreateProperty($"Header_{headerName}", context.Request.Headers[headerName])); } } } }
验证appsettings.json的Serilog配置
确保配置格式正确,示例如下:
{ "Serilog": { "MinimumLevel": "Information", "WriteTo": [ { "Name": "File", "Args": { "path": "logs/log-.txt", "rollingInterval": "Day", "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}" } } ] } }
内容的提问来源于stack exchange,提问作者NV13
相关产品推荐
相关产品推荐

