How to work with logging in EF Core 7
Daniel Khoshbayan
Founder & CEO | +11 years of experience as a C# & .Net developer
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
Create an ASP.NET Core minimal Web API project in Visual Studio 2022
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:
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:
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.
Author, Microsoft MVP (2007 - 2012), Software Architect, Technical Advisor with expertise in .NET technologies
1 年https://www.infoworld.com/article/3679528/how-to-work-with-logging-in-entity-framework-core-7.html