尝试激活 'Serilog.AspNetCore.RequestLoggingMiddleware' 时无法解析“Serilog.Extensions.Hosting.DiagnosticContext”的服务

Unable to resolve service for'Serilog.Extensions.Hosting.DiagnosticContext' while attempting to activate 'Serilog.AspNetCore.RequestLoggingMiddleware'

当我想使用 Custom SerilogRequestLogging 作为中间件时出现以下异常:

System.InvalidOperationException: Unable to resolve service for type 'Serilog.Extensions.Hosting.DiagnosticContext' while attempting to activate 'Serilog.AspNetCore.RequestLoggingMiddleware'.

我在外部库中的自定义 SerilogRequestLogging:

   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