Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable logging in EF Core 3?

I am using Entity Framework Core 3 Preview 5 and ASP.NET Core 3 Preview 5. In my Debug Output Window of Visual Studio 2019 I get no logs from EF Core. I read the documentation, but after that I am even more confused:

  1. According to https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontextoptionsbuilder.useloggerfactory?view=efcore-2.1 logging should be setup automatically:

There is no need to call this method when using one of the 'AddDbContext' methods. 'AddDbContext' will ensure that the ILoggerFactory used by EF is obtained from the application service provider.

That is not my experience though.

  1. I tried to enable logging by injecting the ILoggerFactory to ConfigureServices (I intended to then pass it on to DbContextOptionsBuilder.UseLoggerFactory, but that's not possible anymore, see https://github.com/aspnet/Announcements/issues/353

So, how do I setup logging to the debug output windows in EF Core 3.0? Thanks!

like image 487
stefan.at.wpf Avatar asked Jun 18 '19 09:06

stefan.at.wpf


People also ask

How do I enable sensitive data logging?

Enable Parameter Values in Logging Entity Framework Core provides an option to enable sensitive data logging. To enable this option open the Startup class and in the ConfigureServices function make the following change to the AddDbContext call for the DbContext you want the option on for.

What is logging in .NET Core?

In ASP.NET Core, logging providers store the logs. You can configure multiple logging providers for your application. The default ASP.NET Core configures the following logging providers: Console, Debug, EventSource, and EventLog (on Windows).


2 Answers

Update for 3.0 RTM and later: The log level reverted to Information. Check filtering what is logged in the docs for more details


The close votes are probably because there's no code in the question that can reproduce the problem.

In any case, EF Core logs at the Debug level. The default level used by generic host builder or the Web host builder is Information. The logging level will have to be changed to Trace or Debug.

By default, this code won't log any EF events :

static async Task Main(string[] args)
{
    var host = Host
        .CreateDefaultBuilder(args)             
        .ConfigureServices((context, services) =>
        {
            var configuration = context.Configuration;
            services.AddDbContext<MyContext>(options =>
                options.UseSqlServer(configuration.GetConnectionString("someConnection")));                    
        })                
        .Build();

    using(var ctx=host.Services.GetRequiredService<MyContext>())
    {
        var cnt=await ctx.Customers.CountAsync();
        Console.WriteLine(cnt);
    }            
}

It will only log this event :

info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
  Entity Framework Core 3.0.0-preview6.19304.10 initialized 'ConsolidatorsContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None

To log EF events we need to change the logging level for EF Core events to Trace or Debug through appsettings.json or code. For example, including this in appsettings.json :

    "Logging": {
        "LogLevel": {
            "Microsoft.EntityFrameworkCore":"Debug"
        }
    },

Will log EF events :

  dbug: Microsoft.EntityFrameworkCore.Infrastructure[10401]
        An 'IServiceProvider' was created for internal use by Entity Framework.
  info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
        Entity Framework Core 3.0.0-preview6.19304.10 initialized 'MyContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
  dbug: Microsoft.EntityFrameworkCore.Database.Connection[20000]
        Opening connection to database 'Customers' on server '10.0.0.216'.
  dbug: Microsoft.EntityFrameworkCore.Database.Connection[20001]
        Opened connection to database 'Customers' on server '10.0.0.216'.
  dbug: Microsoft.EntityFrameworkCore.Database.Command[20100]
        Executing DbCommand [Parameters=[], CommandType='Text', CommandTimeout='30']
        SELECT COUNT(*)
        FROM [Customers] AS [c]
  dbug: Microsoft.EntityFrameworkCore.Database.Command[20101]
        Executed DbCommand (42ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
        SELECT COUNT(*)
        FROM [Customers] AS [c]
  4
  dbug: Microsoft.EntityFrameworkCore.Database.Command[20300]
        A data reader was disposed.
  dbug: Microsoft.EntityFrameworkCore.Database.Connection[20002]
        Closing connection to database 'Customers' on server '10.0.0.216'.
  dbug: Microsoft.EntityFrameworkCore.Database.Connection[20003]
        Closed connection to database 'Customers' on server '10.0.0.216'.
  dbug: Microsoft.EntityFrameworkCore.Infrastructure[10407]
        'MyContext' disposed.
like image 115
Panagiotis Kanavos Avatar answered Sep 19 '22 15:09

Panagiotis Kanavos


There is another critical reason why logging may not occur: That comment on AddDbContext() has an unmentioned dependency.

There is no need to call this method when using one of the 'AddDbContext' methods. 'AddDbContext' will ensure that the ILoggerFactory used by EF is obtained from the application service provider.

It only works if your DbContext injects DbContextOptions<T> into the base constructor.

E.g. an auto-generated constructor from Scaffold-DbContext

public MyDbContext(DbContextOptions<MyDbContext> options) 
   : base(options)
{
}

That injected object has been setup with a LoggerFactory, so if you don't do it like this, you will have to manually set the logger in your OnConfiguring() method.

like image 43
Granger Avatar answered Sep 19 '22 15:09

Granger