0

I'm used to develop in .net framework. For a fast login of EF queries I just use Database.Log

public partial class DatabaseContext : DbContext {

public DatabaseContext()
        {
            Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
        }

I search the equivalent in core?

forX
  • 2,063
  • 2
  • 26
  • 47
  • 1
    Does this answer your question? [Entity Framework Core: Log queries for a single db context instance](https://stackoverflow.com/questions/43680174/entity-framework-core-log-queries-for-a-single-db-context-instance) – Panagiotis Kanavos Jun 03 '21 at 19:00
  • The duplicate shows the two available options - either use `optionsBuilder.LogTo` to quickly write eg to the console, or use the .NET Core's logging middleware – Panagiotis Kanavos Jun 03 '21 at 19:02

1 Answers1

0

You can Create a custom LoggerFactory for DI

LoggerFacotry

internal class EFCoreLoggerFactory : LoggerFactory
{
    public EFCoreLoggerFactory() : base()
    {
        base.AddProvider(new EFCoreLoggerProvider());
    }
}

ILoggerProvider

internal class EFCoreLoggerProvider : ILoggerProvider
{
    public ILogger CreateLogger(string categoryName) => new EFCoreLogger(categoryName);
    public void Dispose() { }
}

ILogger

internal class EFCoreLogger : ILogger { private readonly string _categoryName;

    public EFCoreLogger(string categoryName) => this._categoryName = categoryName;

    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, System.Exception exception, Func<TState, System.Exception, string> formatter)
    {
        if (_categoryName == DbLoggerCategory.Database.Command.Name && logLevel == LogLevel.Information)
        {
            var logContent = formatter(state, exception);
            //**Change the log way you want**
            Console.WriteLine(logContent); 
            System.Diagnostics.Trace.WriteLine(logContent);
        }
    }

    public bool IsEnabled(LogLevel logLevel) => true;
    public IDisposable BeginScope<TState>(TState state) => null;
}

Enable LoggerFactory in your DBContext:

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.EnableSensitiveDataLogging(true); //Enable paramters in log
        optionsBuilder.UseLoggerFactory(new EFCoreLoggerFactory());
        base.OnConfiguring(optionsBuilder);
    }
Lei Chi
  • 216
  • 1
  • 14