Search code examples
c#asp.net-coremiddleware.net-5serilog

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


I get the following exception when I want to use Custom SerilogRequestLogging as a middleware:

System.InvalidOperationException: Unable to resolve service for type 'Serilog.Extensions.Hosting.DiagnosticContext' while attempting to activate '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);

                       };
                   });
        }

Then I add it as a middleware in Configure method like this:

 app.UseCustomSerilogRequestLogging();

In 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>();
            });

The extension method in external Library:

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
            );
        }

Solution

  • As mentioned in the comments, your currently shown examples do not show you using .UseSerilog() with the main host builder. While you may have added to the web default builder, based on the exception, it was not added to the service collection, which is what resolves the dependencies when the host is eventually built.

    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>();
            });
    

    Everything else remains the same.

    Reference Serilog.Extensions.Hosting