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.