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.

Postmark Image

Speedy emails, satisfied customers

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay