17

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!

4

2 Answers 2

37

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.
0
5

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.

3
  • It still doesn't work using AddDbContext<MyDbContext>();
    – Wouter
    Nov 15, 2020 at 0:33
  • 4
    No idea how to respond to such a vague, drive-by comment.
    – Granger
    Nov 19, 2020 at 21:44
  • I was trying to get the logger factory from the options but it was always null. As it turns out that's not really needed and then the comment actually makes sense.
    – Wouter
    Nov 20, 2020 at 21:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.