How one can work with logging in EF Core 7


Entity Framework Core (EF Core) is a contemporary, open-source, object-database mapper that simplifies knowledge entry for .NET purposes. EF Core allows you to work with knowledge from quite a lot of sources together with relational databases, non-relational databases, and even in-memory knowledge.

EF Core means that you can write code to execute CRUD actions (create, learn, replace, and delete) with out understanding how the info is continued within the underlying database. Utilizing EF Core, you possibly can retrieve entities from a knowledge retailer, add or change or delete entities, and traverse entity graphs.

In different phrases, EF Core simplifies your knowledge entry by permitting you to jot down code that performs these CRUD operations utilizing .NET objects, with out instantly interacting with the underlying database supplier. This text talks about how you need to use Entity Framework Core to log database exercise when working in ASP.NET Core 7 purposes.

To work with the code examples supplied on this article, it is best to have Visible Studio 2022 Preview put in in your system. Should you don’t have already got a duplicate, you possibly can obtain Visible Studio 2022 Preview right here.

Create an ASP.NET Core minimal Internet API undertaking in Visible Studio 2022 Preview

First off, let’s create an ASP.NET Core undertaking in Visible Studio 2022. Following these steps will create a brand new ASP.NET Core Internet API 6 undertaking in Visible Studio 2022:

  1. Launch the Visible Studio 2022 Preview IDE.
  2. Click on on “Create new undertaking.”
  3. Within the “Create new undertaking” window, choose “ASP.NET Core Internet API” from the record of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new undertaking” window, specify the identify and site for the brand new undertaking.
  6. Optionally test the “Place answer and undertaking in the identical listing” test field, relying in your preferences.
  7. Click on Subsequent.
  8. Within the “Further Data” window proven subsequent, choose .NET 7.0 (Preview) because the framework model you wish to use.
  9. Subsequent, uncheck the test field that claims “Use controllers…” since we’ll be utilizing minimal APIs on this instance. Depart the “Authentication Sort” set as “None” (default).
  10. Be certain that the test packing containers “Allow Docker,” “Configure for HTTPS,” and “Allow Open API Help” are unchecked as we received’t be utilizing any of these options right here.
  11. Click on Create.

This may create a brand new ASP.NET Core 7 Internet API undertaking in Visible Studio 2022. We’ll use this undertaking as an instance logging in EF Core 7 within the subsequent sections of this text.

Logging choices in Entity Framework Core

In Entity Framework Core, logging is used to trace database queries and different operations. Entity Framework Core makes use of the Microsoft.Extensions.Logging framework to log occasions. This framework offers all kinds of logging suppliers that can be utilized to document log messages.

By default, Entity Framework Core will write log messages to the console. Along with utilizing the Microsoft.Extensions.Logging framework, Entity Framework Core additionally helps third-party logging frameworks corresponding to NLog and Serilog. These frameworks can be utilized to jot down log messages to information, databases, or different locations.

Should you intend to make use of EF Core and SQL Server in your software, you’ll need so as to add the Microsoft.EntityFrameworkCore.SqlServer NuGet package deal to your undertaking. Choose the undertaking in Answer Explorer, then right-click and choose “Handle NuGet Packages.” Within the NuGet Bundle Supervisor, seek for Microsoft.EntityFrameworkCore.SqlServer and set up the package deal.

Alternatively, you possibly can set up the package deal through the NuGet Bundle Supervisor console by getting into the command proven beneath.

PM> Set up-Bundle Microsoft.EntityFrameworkCore.SqlServer

Create a Buyer class in .NET Core

Create a category named Buyer in a file having the identical identify with a “.cs” extension and write the next code in there:

public class Buyer
    public int Id { get; set; }
    public string FirstName { get; set; } = string.Empty;
    public string LastName { get; set; } = string.Empty;

Configure logging in Entity Framework Core

You’ll be able to reap the benefits of logging in Entity Framework Core in both of two methods:

  • Use the UseLoggerFactory extension methodology.
  • Use the ILoggerProvider interface.

The UseLoggerFactory extension methodology is the beneficial technique to configure logging in EF Core, because it permits for a extra versatile configuration. To make use of the UseLoggerFactory extension methodology, merely add it to your DbContext class as proven within the code snippet given beneath.

utilizing Microsoft.Extensions.Logging;
public class MyDbContext : DbContext
   public MyDbContext(DbContextOptions choices)
        : base(choices){ }
   protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
   ILoggerFactory loggerFactory = new LoggerFactory();

Alternatively, you possibly can configure logging by utilizing the ILoggerProvider interface as proven within the code snippet given beneath.

builder.Companies.AddDbContext((supplier, choices) =>
    var loggerFactory = supplier.GetRequiredService();

Ship EF Core log knowledge to the console

You should utilize the next code to configure your DbContext occasion to make use of  LoggerFactory.


To allow EF Core to log knowledge to the console, you need to use the next code.


Full supply code of our DbContext class

The whole supply code of the DbContext class is given beneath in your reference.

public partial class DemoDbContext: DbContext
    public DemoDbContext()
    public DemoDbContext(DbContextOptions < DemoDbContext > choices): base(choices)
    public digital DbSet < Buyer > Buyer
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    protected override void OnModelCreating(ModelBuilder modelBuilder)
        modelBuilder.Entity < Buyer > (entity =>
            entity.Property(e => e.FirstName).IsRequired().HasMaxLength(50);
            entity.Property(e => e.LastName).IsRequired().HasMaxLength(50);

Versatile logging with EF Core

Logging is a vital part of any software for figuring out and analyzing issues that may happen at runtime. When working with EF Core, you possibly can log knowledge to built-in log targets in addition to combine your software with third-party logging frameworks to ship knowledge to preconfigured log targets.

Copyright © 2022 IDG Communications, Inc.

Supply hyperlink