16

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://learn.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!

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
stefan.at.kotlin
  • 15,347
  • 38
  • 147
  • 270
  • Have you taken a look on it please: https://learn.microsoft.com/en-us/ef/core/miscellaneous/logging – TanvirArjel Jun 18 '19 at 14:24
  • 1
    The reason for the close votes is that you *didn't* post any code that can reproduce the issue. For all anyone knows, you may not have enabled logging at all, or log only information messages. There are questions [like this one](https://stackoverflow.com/questions/56419481/suppress-ef-core-3-0-x-initialized-msg) that ask how to turn down logging. The default logging configuration writes to the console, debug output and event log – Panagiotis Kanavos Jun 18 '19 at 14:31
  • 1
    OK, I understand. I meanwhile also found the reason: a breaking change in EF Core 3.0. SQL queries are now only shown in Debug mode. I should have checked more if there was an output from EF core at all. I was heading in the wrong direction. The mentioned breaking change: https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/breaking-changes#query-execution-is-logged-at-debug-level also see https://stackoverflow.com/questions/55997906/net-core-3-0-consoleloggerfactory-for-sqlite?rq=1 – stefan.at.kotlin Jun 18 '19 at 15:13
  • 2
    One should note this change will get reverted again: https://github.com/aspnet/EntityFrameworkCore/issues/14523 – stefan.at.kotlin Jun 18 '19 at 15:17

2 Answers2

36

Update for 3.0 RTM and later: The log level reverted to Information. Check filtering what is logged in the docs for more details. See also the list of categories that can be used for filtering in appsettings.json.


EF Core logs at the Debug level, but the default level used by the host builder is Information. The logging level will thus have to be manually set 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.
Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
  • Thanks! Seems we were replying in parallel though, see my comments above. Note that the required logging level will be changed back to Information in a future release: https://github.com/aspnet/EntityFrameworkCore/issues/14523 – stefan.at.kotlin Jun 18 '19 at 15:39
  • @stefan.at.wpf the correct link for that is https://github.com/aspnet/EntityFrameworkCore/issues/15888 – Panagiotis Kanavos Jun 18 '19 at 15:41
4

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.

Granger
  • 3,639
  • 4
  • 36
  • 34