Adding Logging in Entity Framework Core

Adding Logging in Entity Framework Core

logging efcore console aspnet core Adding Logging in Entity Framework Core | TheCodeBuzz

In this article, we will see how to enable or Logging in Entity Framework Core.

We often find such needs where we need to log SQL CRUD commands and queries getting executed for Debugging or Informational or troubleshooting purposes in EF Core.

Today in this article, we will cover below aspects,

In this article, we shall two basic techniques of enabling the logging in Entity framework core commands execution.

Both these techniques can be applied to ASP.NET Core or Console or any Desktop application(based on .NET Core).

  • Logging through Configuration (No code change required)
  • Logging using LoggerFactory

Getting Started

I already have a sample .NET Core application that uses DBContext as below.

References: Getting Started with Entity Framework .NET Core

logging Entity framework DBContext settings Adding Logging in Entity Framework Core | TheCodeBuzz

Now you may access DBContext using Dependency injection or accessing it directly, either way, below both discussed techniques, work fine.

Logging in Entity Framework Core Enable – Configuration

Please note that Entity Framework Core has built in the logging support in .NET Core once required EF components are installed in the applications.

Let’s use the ‘appsettings.json‘ Configuration as below,

 "Microsoft.EntityFrameworkCore": "Information"

logging Entity framework aspnet core using configuration Adding Logging in Entity Framework Core | TheCodeBuzz

The above configuration can be enabled for debugging, Information or Warning, etc. Log level type as needed.

Let execute any CRUD operation, you shall see magically all the logs are getting captured on based on the logging configuration you have enabled.

logging Entity framework console asp net core 1 Adding Logging in Entity Framework Core | TheCodeBuzz

The above approach works fine seamlessly for ASP.NET Core applications.

Applications like Console, and Windows Form applications if using Dependency Injection the above configuration will work too.

Please make sure to enable logging configuration in the IoC container.

Please refer to a few articles on Implementing DI in a Console application and Windows Form application for understanding more on the same.

To use this option , please make sure to enable your DBContext class using DbContextOptions. This option make sure configurations are loaded from apps settings.

image 3 Adding Logging in Entity Framework Core | TheCodeBuzz

If using EFCore Scaffolding commands to generate the scaffolding then DbContextOptions gets added by default.

Enable logging using LoggerFactory

In this example, we shall create a static instance of the LoggerFactory class then we will pass this object in the OnConfiguring and invoke Method UseLoggerFactory().

    public partial class EmployeeContext : DbContext
    {

        public static readonly ILoggerFactory _loggerFactory = LoggerFactory.Create(builder =>
        {
            builder.AddConsole();
        });

        public EmployeeContext()
        {
        }

        public EmployeeContext(DbContextOptions<EmployeeContext> options)
            : base(options)
        {
        }

..
        }


Above we have enabled console logging. If needed please use a few additional options for creating logging.

Update the OnConfiguring () by adding UseLoggerFactory() using the above created _loggerFactory instance.

 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseLoggerFactory(_loggerFactory);
            optionsBuilder.EnableSensitiveDataLogging();
            if (!optionsBuilder.IsConfigured)
            { 
                 optionsBuilder.UseSqlServer("Server=localhost\\SQLEXPRESS;Database=master;Trusted_Connection=True;");
            }
        }

Let’s run any CRUD operation on the DBContext object, You shall see the result as below,

logging Entity framework aspnet core 1 Adding Logging in Entity Framework Core | TheCodeBuzz

It’s recommended using static singleton instance of LoggerFactory object for all database operations.

That’s all! Happy coding!

Does this help you fix your issue?

Do you have any better solutions or suggestions? Please sound off your comments below.

Summary

We often find needs for logging SQL CRUD commands or queries getting executed for Debugging or Informational or troubleshooting purposes in EF Core. In this article, we looked at enabling logging in the Entity Framework layer using simple easy steps.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



6 thoughts on “Adding Logging in Entity Framework Core”

    1. Hey EN, Console logs will be available on the host directly. If debugging in Visual Studio – Please go to Menu -> output -> Show output from -> Select your app with ASP.NET Core Webserver. Hope this helps. Thanks for your Query . Have a Great Day!

Leave a Comment

Your email address will not be published. Required fields are marked *