How to show queries generated by EF core

1

A while ago, with a simple code within my context, it would display the queries generated by EF6 in the console or even write to a txt file ...

However, today I use the Entity Framework Core in an asp.net core (MVC) application and wanted to do the same, does anyone have any idea how I can do this?

    
asked by anonymous 03.10.2018 / 14:39

1 answer

2

One way to do this is by implementing a log provider.

In your EF context class you override the OnConfiguring method by informing the log provider you will create:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    var lf = new LoggerFactory();
    lf.AddProvider(new MyLoggerProvider());
    optionsBuilder.UseLoggerFactory(lf);
}

To create your provider, create a class (in this example I created the class MyLoggerProvider ) that implements the interface ILoggerProvider .

Implement the CreateLogger method by returning a class instance (in this example I created the MyLogger class) that implements ILogger , when implementing the Log method of this interface, you specify the path of the file.

Once the application has been run, the log with the EF queries will be generated.

Below the code of the classes created:

using Microsoft.Extensions.Logging;
using System;
using System.IO;

public class MyLoggerProvider : ILoggerProvider
{
    public ILogger CreateLogger(string categoryName)
    {
        return new MyLogger();
    }

    public void Dispose()
    { }        
}

public class MyLogger : ILogger
{
    public bool IsEnabled(LogLevel logLevel)
    {
        return true;
    }

    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
    {
        File.AppendAllText(@"C:\temp\logDaAplicacao.txt", formatter(state, exception));
        Console.WriteLine(formatter(state, exception));
    }

    public IDisposable BeginScope<TState>(TState state)
    {
        return null;
    }
}

This example, I found here and tested the site to validate, worked fine.

At documentation you also have an example of how to log in to the console.

    
03.10.2018 / 18:36