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.

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

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