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