-1

I am new in .NET Core web API. I want to write Exception log data into database.

I am able to catch all exception, but i haven't idea where will be next implementation for writing data into database. For database i am using postgresql.

statup.cs

app.UseExceptionHandler(a => a.Run(async context =>
{
    var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
    var exception = exceptionHandlerPathFeature.Error;

    var result = JsonConvert.SerializeObject(new { error = exception.Message });
    context.Response.ContentType = "application/json";
    await context.Response.WriteAsync(result);
}));
ANJYR
  • 2,583
  • 6
  • 39
  • 60

1 Answers1

0

I assume you are using the code provided by Andrei here : https://stackoverflow.com/a/38935583

What I could advise you would be to register an external middle-ware, such as the first approach Andrei proposed in his answer. Then, in the middle-ware, you could register a service which would be responsible of calling the data access layer. This DAL would offer a method to write your logs into a database.

This article will help you to configure your app to work with Entity Framework and Postgres, and to code the layers between : https://www.compose.com/articles/code-first-database-design-with-entity-framework-and-postgresql/

To resume :

  • Configure your app to use EF Core with Postgres
  • Create the Entities you'll need to work with
  • Create a Data Access Layer to allow your app to play with data
  • Code a service layer and add a service responsible to write your logs
  • Get your Exception middle-ware out of startup.cs and make it call your log service

That said, the best approach would be to use a logger such as Log4net or Serilog. This way, you could benefit from a central place to get logs, and you could "send" those logs to db, files, mail, etc.

Skrface
  • 1,388
  • 1
  • 12
  • 20