DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

6 2

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.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay