How to log queries using Entity Framework 7?

前端 未结 10 1408
清歌不尽
清歌不尽 2020-12-15 23:55

I am using Entity Framework 7 on the nightly build channel (right now I\'m using version EntityFramework.7.0.0-beta2-11524) and I\'m trying to log the queries that EF genera

10条回答
  •  时光说笑
    2020-12-16 00:27

    I struggled with all the above answers as the EF bits kept changing, so the code wouldn't compile. As of today (19Feb2016) with EF7.0.0-rc1-final (Prerelease) and SQLite, here's what works for me:

    From the EF7 documentation:

    using System;
    using System.IO;
    using Microsoft.Extensions.Logging;
    
    namespace EFLogging
    {
        public class EFLoggerProvider : ILoggerProvider
        {
            public ILogger CreateLogger(string categoryName)
            {
                return new EFLogger();
            }
    
            public void Dispose()
            {
                // N/A
            }
    
            private class EFLogger : ILogger
            {
                public IDisposable BeginScopeImpl(object state)
                {
                    return null;
                }
    
                public bool IsEnabled(LogLevel logLevel)
                {
                    return true;
                }
    
                public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func formatter)
                {
                    File.AppendAllText(@".\EF.LOG", formatter(state, exception));
                    Console.WriteLine(formatter(state, exception));
                }
            }
        }
    }
    

    Using some ideas above and the EF7 Docs:

    using System;
    using Microsoft.Data.Entity;
    using Microsoft.Data.Entity.Infrastructure;
    using Microsoft.Extensions.DependencyInjection;  // Add this to EF7 docs code
    using Microsoft.Extensions.Logging;
    
    namespace DataAccessLayer
    {
        public static class DbContextExtensions
        {
            public static void LogToConsole(this DbContext context)
            {
                var serviceProvider = context.GetInfrastructure();
                var loggerFactory = serviceProvider.GetService();
                loggerFactory.AddProvider(new EFLoggerProvider(logLevel));
            }
        }
    }
    

    EDIT: @jnm2 pointed out if you add "using Microsoft.Extensions.DependencyInjection", the EF7 docs ARE correct. Thanks!

    And finally, in my App.OnStartup method:

    using (var db = new MyDbContext())
    {
        db.LogToConsole();
    }
    

    This code will create a log file and also output logging info to the Visual Studio output window. I hope this helps -- I'm sure in a few weeks, the bits will change again.

提交回复
热议问题