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.
You tried the
UseLoggerFactory()
?– Leandro Angelo
No, but I will research on and implement, vlw!
– Márcio Sebastião
If you encounter any difficulty, edit your question with the attempt and we will resolve ;)
– Leandro Angelo