Friday, November 11, 2022
HomeITThe right way to work with logging in EF Core 7

The right way to 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 lets you work with knowledge from a wide range 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’ll be able to retrieve entities from an information retailer, add or change or delete entities, and traverse entity graphs.

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

To work with the code examples offered on this article, you must have Visible Studio 2022 Preview put in in your system. Should you don’t have already got a replica, you’ll be able to obtain Visible Studio 2022 Preview right here.

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

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

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

It will create a brand new ASP.NET Core 7 Internet API challenge in Visible Studio 2022. We’ll use this challenge as an example 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 gives all kinds of logging suppliers that can be utilized to file 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 akin to NLog and Serilog. These frameworks can be utilized to put in writing log messages to recordsdata, databases, or different locations.

Should you intend to make use of EF Core and SQL Server in your software, you will want so as to add the Microsoft.EntityFrameworkCore.SqlServer NuGet package deal to your challenge. Choose the challenge in Resolution 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’ll be able to set up the package deal through the NuGet Bundle Supervisor console by coming 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 title 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 benefit from logging in Entity Framework Core in both of two methods:

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

The UseLoggerFactory extension technique is the really helpful method to configure logging in EF Core, because it permits for a extra versatile configuration. To make use of the UseLoggerFactory extension technique, 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)
   {
       optionsBuilder.UseLoggerFactory(loggerFactory);
       base.OnConfiguring(optionsBuilder);
   }
   ILoggerFactory loggerFactory = new LoggerFactory();
}

Alternatively, you’ll be able to configure logging through the use of the ILoggerProvider interface as proven within the code snippet given beneath.


builder.Providers.AddDbContext((supplier, choices) =>
{
    var loggerFactory = supplier.GetRequiredService();
    choices.UseLoggerFactory(loggerFactory);
});

Ship EF Core log knowledge to the console

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


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

To allow EF Core to log knowledge to the console, you should utilize the next code.


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

Full supply code of our DbContext class

The entire supply code of the DbContext class is given beneath to your reference.


public partial class DemoDbContext: DbContext
{
    public DemoDbContext()
    {}
    public DemoDbContext(DbContextOptions < DemoDbContext > choices): base(choices)
    {}
    public digital DbSet < Buyer > Buyer
    {
        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 < 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 an important element of any software for figuring out and analyzing issues that may happen at runtime. When working with EF Core, you’ll be able to 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.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments