EntityFrameworkCore Logging in ASP.NET Core


Julie LermanI was reading my newest issue of MSDN Magazine and came across Julie Lerman's great article on how to configure Logging in Entity Framework Core. While this is great information, it only covered logging Entity Framework Core from a non-ASP.NET Core project so I figured I'd explain how to do it in ASP.NET Core.

The biggest thing that is different from the way that Julie shows this is that ASP.NET Core automatically wires up the ASP.NET Core logger to the context when it injects a context into your project. So to see Entity Framework Core logging, you need to enable it your ASP.NET Core logging, not in Entity Framework Core.

First let's talk about how Logging is handled in ASP.NET Core. In your Program.cs file, the WebHost.CreateDefaultBuilder() automatically sets up logging:

  public class Program
  {
    public static void Main(string[] args)
    {
      CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args) // <-- Logging Added Here
            .UseStartup<Startup>();
  }

This setup turns on four types of logging by default:

                .ConfigureLogging((hostingContext, logging) =>
                {
                    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                    logging.AddConsole();
                    logging.AddDebug();
                    logging.AddEventSourceLogger();
                })

GitHub Link

Because of this, we can simply use the WebHost facility to modify the logging:

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args) // <-- Logging Added Here
            .ConfigureLogging(ConfigLogging)
            .UseStartup<Startup>();

    static void ConfigLogging(ILoggingBuilder bldr)
    {
      bldr.AddFilter(DbLoggerCategory.Database.Connection.Name, LogLevel.Information);
    }

The ConfigureLogging method allows us to be called after logging is configured to add our own code. In this case, we can use the DbLoggerCategory class (like Julie mentions) to just add a filter for the category of log and make it appear based on our log level.

This is actually easier than that even. If you noticed the logging.AddConfiguration() in the default configuration, you'll see that it's actually getting logging information (e.g. filters) from the configuration file.

So in your default configuration file, you're likely to see something like this:

// appSettings.json
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Error"
    }
  },

This translates into a filter for all messages at the Information level, and any message with the "category" of "Microsoft" is setup as error. These are just lists of logging filters, so we can discern the name of the EntityFrameworkCore categories from the DbLoggerCategory class. For example, to enable Connection logs from EF Core, just add:

  "Logging": {
    "LogLevel": {
      "Default": "Error",
      "Microsoft": "Error",
      "Microsoft.EntityFrameworkCore.Database.Command": "Information"
    }
  },

This works because the DbLoggerCategory base name is "Microsoft.EntityFrameworkCore" (which you can see in the github repo: here). And the rest of the names follow the class heirarchy.

So, in most cases, the best way to turn this on in ASP.NET Core is to just change the configuration to turn it on when you need it. Yeah, really.


Ready to Learn Vue with ASP.NET Core?

Shawn's 4-hour course will get you up to speed in no time. Vue.js is a great middle-ground between React and Angular for people who don't like the complexity of Angular, and the overly componentized React. Learn today at Wilder Minds Training!

Enroll Today


Shawn
Shawn Wildermuth
Author, Teacher, and Coach




My Courses

Wilder Minds Training
Vue.js by Example (Now Available)
Bootstrap 4 by Example
Intro to Font Awesome 5 (Free Course)
Pluralsight
Less: Getting Started (Coupon Available)
Building a Web App with ASP.NET Core, MVC6, EF Core, Bootstrap and Angular (updated for 2.1)
Using Visual Studio Code for ASP.NET Core Projects
Implementing ASP.NET Web API
Web API Design

Application Name WilderBlog Environment Name Production
Application Ver v4.0.30319 Runtime Framework x86
App Path D:\home\site\wwwroot\ Runtime Version .NET Core 4.6.26919.02
Operating System Microsoft Windows 10.0.14393 Runtime Arch X86