How to work with logging in EF Core 7

Learn how you can use Entity Framework Core to log data to the console, SQL Server, and other log targets when working with ASP.NET Core 7 applications.

logs
Greg Lobinski (CC BY 2.0)

Entity Framework Core (EF Core) is a modern, open-source, object-database mapper that simplifies data access for .NET applications. EF Core enables you to work with data from a variety of sources including relational databases, non-relational databases, and even in-memory data.

EF Core allows you to write code to execute CRUD actions (create, read, update, and delete) without understanding how the data is persisted in the underlying database. Using EF Core, you can retrieve entities from a data store, add or change or delete entities, and traverse entity graphs.

In other words, EF Core simplifies your data access by allowing you to write code that performs those CRUD operations using .NET objects, without directly interacting with the underlying database provider. This article talks about how you can use Entity Framework Core to log database activity when working in ASP.NET Core 7 applications.

To work with the code examples provided in this article, you should have Visual Studio 2022 Preview installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 Preview here.

Create an ASP.NET Core minimal Web API project in Visual Studio 2022 Preview

First off, let’s create an ASP.NET Core project in Visual Studio 2022. Following these steps will create a new ASP.NET Core Web API 6 project in Visual Studio 2022:

  1. Launch the Visual Studio 2022 Preview IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  7. Click Next.
  8. In the “Additional Information” window shown next, select .NET 7.0 (Preview) as the framework version you want to use.
  9. Next, uncheck the check box that says “Use controllers…” since we’ll be using minimal APIs in this example. Leave the “Authentication Type” set as “None” (default).
  10. Ensure that the check boxes “Enable Docker,” “Configure for HTTPS,” and “Enable Open API Support” are unchecked as we won’t be using any of those features here.
  11. Click Create.

This will create a new ASP.NET Core 7 Web API project in Visual Studio 2022. We’ll use this project to illustrate logging in EF Core 7 in the subsequent sections of this article.

Logging options in Entity Framework Core

In Entity Framework Core, logging is used to track database queries and other operations. Entity Framework Core uses the Microsoft.Extensions.Logging framework to log events. This framework provides a wide variety of logging providers that can be used to record log messages.

By default, Entity Framework Core will write log messages to the console. In addition to using the Microsoft.Extensions.Logging framework, Entity Framework Core also supports third-party logging frameworks such as NLog and Serilog. These frameworks can be used to write log messages to files, databases, or other destinations.

If you intend to use EF Core and SQL Server in your application, you will need to add the Microsoft.EntityFrameworkCore.SqlServer NuGet package to your project. Select the project in Solution Explorer, then right-click and select “Manage NuGet Packages.” In the NuGet Package Manager, search for Microsoft.EntityFrameworkCore.SqlServer and install the package.

Alternatively, you can install the package via the NuGet Package Manager console by entering the command shown below.

PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer

Create a Customer class in .NET Core

Create a class named Customer in a file having the same name with a ".cs" extension and write the following code in there:

 
public class Customer
{
    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 can take advantage of logging in Entity Framework Core in either of two ways:

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

The UseLoggerFactory extension method is the recommended way to configure logging in EF Core, as it allows for a more flexible configuration. To use the UseLoggerFactory extension method, simply add it to your DbContext class as shown in the code snippet given below.

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

Alternatively, you can configure logging by using the ILoggerProvider interface as shown in the code snippet given below.


builder.Services.AddDbContext((provider, options) =>
{
    var loggerFactory = provider.GetRequiredService();
    options.UseLoggerFactory(loggerFactory);
});

Send EF Core log data to the console

You can use the following code to configure your DbContext instance to use  LoggerFactory.


optionsBuilder.UseLoggerFactory(loggerFactory)
.EnableSensitiveDataLogging()
.UseSqlServer("Server=JOYDIP;Database=DemoDb;Trusted_Connection=True;");

To enable EF Core to log data to the console, you can use the following code.


optionsBuilder.UseSqlServer
("Server=JOYDIP;Database=DemoDb;Trusted_Connection=True;").
LogTo(Console.WriteLine).EnableDetailedErrors();

Complete source code of our DbContext class

The complete source code of the DbContext class is given below for your reference.


public partial class DemoDbContext: DbContext
{
    public DemoDbContext()
    {}
    public DemoDbContext(DbContextOptions < DemoDbContext > options): base(options)
    {}
    public virtual DbSet < Customer > Customer
    {
        get;
        set;
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=JOYDIP;Database=DemoDb;Trusted_Connection=True;").LogTo(Console.WriteLine).EnableDetailedErrors();
        base.OnConfiguring(optionsBuilder);
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity < Customer > (entity =>
        {
            entity.Property(e => e.FirstName).IsRequired().HasMaxLength(50);
            entity.Property(e => e.LastName).IsRequired().HasMaxLength(50);
        });
    }
}
 

Flexible logging with EF Core

Logging is a crucial component of any application for identifying and analyzing problems that can occur at runtime. When working with EF Core, you can log data to built-in log targets as well as integrate your application with third-party logging frameworks to send data to preconfigured log targets.

Copyright © 2022 IDG Communications, Inc.

How to choose a low-code development platform