DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

Entity Framework Core: Logging

When we use EF Core in our application, we want to see generated query for debug purpose. And its actually quite easy to set it up.

ASP.NET

The easiest way to configure it is in appsettings.json. Add EF related category and level in LogLevel node. We can find categories choices here

{  
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.EntityFrameworkCore.Database": "Information"
    }
  }
...
}
Enter fullscreen mode Exit fullscreen mode

C# code

If configuration won't work, we can always use C# code to enable logging.

We can add logging settings at OnConfiguring method of our DbContext class. Following example set:

  • Information LogLevel
  • Database category
  • Output to debug console (Visual Studio output)
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
    options
        .LogTo(m => Debug.WriteLine(m), new[] { DbLoggerCategory.Database.Name }, LogLevel.Information)
        .EnableSensitiveDataLogging()
        .UseXXX();
}
Enter fullscreen mode Exit fullscreen mode

If we want to log to console, we can simply change the first argument.

protected override void OnConfiguring(DbContextOptionsBuilder options)
{
    options
        .LogTo(Console.WriteLine, new[] { DbLoggerCategory.Database.Name }, LogLevel.Information)
        .EnableSensitiveDataLogging()
        .UseXXX();
}
Enter fullscreen mode Exit fullscreen mode

Summary

Of course we have so many more ways to configure logging with more granular level. See EF Logging Doc for detail.

Top comments (0)