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?

2

1 Answer 1

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);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

nothing personal, just an awesome facepalm moment -_-

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.