Home > Software engineering >  Add logging if ModelStats is invalid
Add logging if ModelStats is invalid

Time:05-20

we're using the InvalidModelStateResponseFactory to standardize the layout of error responses. This works great.

services.Configure<ApiBehaviorOptions>(options =>
{                
    options.InvalidModelStateResponseFactory = context =>
    {
       var result = new BadRequestObjectResult(new BadRequestErrorResponse(context.ModelState));
       return result;
    };
});

But now the need has come up to also log these errors. How would we do that? Add the ILogger to this part of the code or create a custom Middleware/ActionFilter?

Addtitional Info, we use Seriloger:

public static void Main(string[] args)
{
    // The initial "bootstrap" logger is able to log errors during start-up. It's completely replaced by the
    // logger configured in `UseSerilog()` below, once configuration and dependency-injection have both been
    // set up successfully.
    Log.Logger = new LoggerConfiguration()
        .WriteTo.Console()
        .CreateBootstrapLogger();

Left out the rest for brevity

public static IHostBuilder CreateHostBuilder(string[] args)
{
    return Host.CreateDefaultBuilder(args)
        .UseSerilog((context, services, configuration) => configuration
            .ReadFrom.Configuration(context.Configuration)
            .ReadFrom.Services(services)
            .Enrich.FromLogContext()
        )
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });
}

CodePudding user response:

You can retrieve the registered logger like this through the context:

var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger>();

UPDATE #1 The UseSeriLog registers an ILoggerFactory rather than an explicit ILogger.

In that case you have to modify the above code like this:

var factory = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>();
var logger = factory.CreateLogger("InvalidModelState");
  • Related