Skip to content

Version320 Capture EF Core logging

Jon P Smith edited this page Jan 4, 2021 · 1 revision

Version 3.2.0 - Tools for capturing EF Core logging

It is sometimes useful for capture the logging output of EF Core, maybe to see how EF Core translates your query to SQL or how it would create your database. This is done via one of the Sqlite/SqlServer options methods ending in ...WithLogging.

NOTE: The methods shown here are new in version 1.6.0 of the library. The older SetupLogging is now obsolete as the new version doesn't have the 'bleed' problem that the SetupLogging method has.

a. Capturing the logs into a list

Here is an example for capturing the logging into a list so that you can check the SQL it EF Core is outputting.

[Fact]
public void TestEfCoreLoggingCheckSqlOutput()
{
    //SETUP
    var logs = new List<LogOutput>();
    var options = SqliteInMemory.CreateOptionsWithLogging<BookContext>(
         log => logs.Add(log));
    using (var context = new BookContext(options))
    {
        context.Database.EnsureCreated();

        //ATTEMPT 
        context.Books.Count();

        //VERIFY
        logs.Last().Message.ShouldEndWith(
             "SELECT COUNT(*)\r\nFROM \"Books\" AS \"p\"\r\nWHERE \"p\".\"SoftDeleted\" = 0");
    }
}

b. Sending the logs to the unit test output window

The typical output is to the unit test output window using xUnit's ITestOutputHelper output interface. Here is an example that outputs the SQL that EF Core uses for creating a new SQL Server database. The the Ef Core logs appear to the unit test window (Test Explorer->Output, Resharper->Output window).

[RunnableInDebugOnly]
public void CaptureSqlEfCoreCreatesDatabaseToConsole()
{
    //SETUP
    var options = this.CreateUniqueClassOptionsWithLogging<BookContext>(
         log => _output.WriteLine(log.Message));
    using (var context = new BookContext(options))
    {

        //ATTEMPT
        context.Database.EnsureDeleted();
        context.Database.EnsureCreated();
    }
}

See the class LogOutput for information on various parts of the log.

Clone this wiki locally