How to show queries generated by EF core

Asked

Viewed 48 times

1

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

However, today I use Entity Framework Core, in an Asp.net core (MVC) application and wanted to do the same, someone has an idea of how I do it?

  • 1

    You tried the UseLoggerFactory()?

  • No, but I will research on and implement, vlw!

  • 1

    If you encounter any difficulty, edit your question with the attempt and we will resolve ;)

1 answer

2


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

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

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

To create your Fortune, create a class (in this example I created the class Myloggerprovider) implementing the interface ILoggerProvider.

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

When running the application, the log with the EF queries will be generated.

Below the code of the created classes:

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;
    }
}

That example, I found here and tested site to validate, worked right.

In the documentation also has example of how to log into the console.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.