当我想使用自定义SerilogRequestLogging
作为中间件时,我得到以下例外:
系统。InvalidOperationException:无法解析服务类型"Serilog.Extensions.Hosting。诊断上下文',试图激活"Serilog.AspNetCore.RequestLoggingMiddleware"。
My Custom SerilogRequestLogging in external Library:
public static IApplicationBuilder UseCustomSerilogRequestLogging(this IApplicationBuilder app)
{
return app.UseSerilogRequestLogging(options =>
{
options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
{
diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
diagnosticContext.Set("RequestMethod", httpContext.Request.Method);
diagnosticContext.Set("RequestProtocol", httpContext.Request.Protocol);
diagnosticContext.Set("RequestPath", httpContext.Request.Path);
diagnosticContext.Set("RequestRemoteAddress", httpContext.Connection.RemoteIpAddress);
};
});
}
然后我将其作为中间件添加到Configure方法中,如下所示:
app.UseCustomSerilogRequestLogging();
在program.cs:public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseSerilog((provider, context, loggerConfig) =>
{
loggerConfig.Configure(provider, Configuration);
});
webBuilder.UseStartup<Startup>();
});
外部库的扩展方法:
public static void Configure(this LoggerConfiguration loggerConfig,
IServiceProvider provider, IConfiguration config)
{
var sqlserverConnectionString = config["ConnectionStrings:S1"];
var sqlserverLogTable = config["Logging:S2"];
var rollingFileName = config["Logging:S3"];
//SQL CONFIGURATION HERE TO REDUCE THE NUMBER OF LINES...
loggerConfig
.ReadFrom.Configuration(config)
.Enrich.FromLogContext()
.Enrich.WithMachineName()
.Enrich.WithAssemblyName()
.Enrich.WithAssemblyVersion()
.WriteTo.File(rollingFileName, restrictedToMinimumLevel: LogEventLevel.Verbose)
.WriteTo.Seq(seqAddress)
.WriteTo.MSSqlServer(
connectionString: sqlserverConnectionString,
sinkOptions: sinkOpts,
columnOptions: columnOpts
);
}
正如评论中提到的,当前显示的示例并没有显示您将.UseSerilog()
与主主机构建器一起使用。虽然您可能已经添加到web默认构建器中,但基于异常,它没有添加到服务集合中,这是在最终构建主机时解决依赖关系的方法。
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog() //<-- THIS WAS MISSING HERE
.ConfigureWebHostDefaults(webBuilder => {
webBuilder.UseSerilog((provider, context, loggerConfig) => {
loggerConfig.Configure(provider, Configuration);
});
webBuilder.UseStartup<Startup>();
});
其他内容保持不变。
参考Serilog.Extensions.Hosting