使用EF Core(或任何ORM),我想要跟踪ORM在我的软件中的某些操作期间对数据库进行的查询的数量。
我之前在Python下使用过SQLAlchemy,在那个堆栈上设置它非常容易。我通常使用单元测试来断言针对内存中的SQLite数据库为场景所做的查询的数量。
现在我想使用EF Core做同样的事情,并且已经查看了日志记录文档。
在我的测试设置代码中,我按照文档中所说的做:
using (var db = new BloggingContext())
{
var serviceProvider = db.GetInfrastructure<IServiceProvider>();
var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
loggerFactory.AddProvider(new MyLoggerProvider());
}
但是我遇到了一些问题,我怀疑这些问题是由以下原因引起的(也来自于文档):
您只需要用一个上下文实例注册记录器。一旦您注册了它,它将用于同一AppDomain中上下文的所有其他实例。
我在测试中看到的问题表明,我的记录器实现是在多个上下文中共享的(这与我阅读的文档是一致的)。而且,由于a)我的测试运行器并行地运行测试,b)我的整个测试套件创建了数百个db上下文--它工作得不是很好。
问题/议题:
调用DbContextoptionsBuilder.UseLoggerFactory(loggerFactory)
方法来记录特定上下文实例的所有SQL输出。可以在上下文的构造函数中注入记录器工厂。
下面是一个用法示例:
//this context writes SQL to any logs and to ReSharper test output window
using (var context = new TestContext(_loggerFactory))
{
var customers = context.Customer.ToList();
}
//this context doesn't
using (var context = new TestContext())
{
var products = context.Product.ToList();
}
通常,我使用这个特性进行手动测试。为了保持原始上下文类的清洁,使用重写的onConfiguring
方法声明派生的可测试上下文:
public class TestContext : FooContext
{
private readonly ILoggerFactory _loggerFactory;
public TestContext() { }
public TestContext(ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseLoggerFactory(_loggerFactory);
}
}
它足以记录SQL查询。不要忘记在将LoggerFactory
传递给上下文之前将合适的记录器(如控制台)附加到它。
我们可以在测试类构造函数中创建LoggerFactory
:
public class TestContext_SmokeTests : BaseTest
{
public TestContext_SmokeTests(ITestOutputHelper output)
: base(output)
{
var serviceProvider = new ServiceCollection().AddLogging().BuildServiceProvider();
_loggerFactory = serviceProvider.GetService<ILoggerFactory>();
_loggerFactory.AddProvider(new XUnitLoggerProvider(this));
}
private readonly ILoggerFactory _loggerFactory;
}
测试类派生自BaseTest
,它支持对XUnit
输出的写入:
public interface IWriter
{
void WriteLine(string str);
}
public class BaseTest : IWriter
{
public ITestOutputHelper Output { get; }
public BaseTest(ITestOutputHelper output)
{
Output = output;
}
public void WriteLine(string str)
{
Output.WriteLine(str ?? Environment.NewLine);
}
}
最棘手的部分是实现接受iWriter
作为参数的日志记录提供程序:
public class XUnitLoggerProvider : ILoggerProvider
{
public IWriter Writer { get; private set; }
public XUnitLoggerProvider(IWriter writer)
{
Writer = writer;
}
public void Dispose()
{
}
public ILogger CreateLogger(string categoryName)
{
return new XUnitLogger(Writer);
}
public class XUnitLogger : ILogger
{
public IWriter Writer { get; }
public XUnitLogger(IWriter writer)
{
Writer = writer;
Name = nameof(XUnitLogger);
}
public string Name { get; set; }
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception,
Func<TState, Exception, string> formatter)
{
if (!this.IsEnabled(logLevel))
return;
if (formatter == null)
throw new ArgumentNullException(nameof(formatter));
string message = formatter(state, exception);
if (string.IsNullOrEmpty(message) && exception == null)
return;
string line = $"{logLevel}: {this.Name}: {message}";
Writer.WriteLine(line);
if (exception != null)
Writer.WriteLine(exception.ToString());
}
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
public IDisposable BeginScope<TState>(TState state)
{
return new XUnitScope();
}
}
public class XUnitScope : IDisposable
{
public void Dispose()
{
}
}
}
我们已经结束了!所有SQL日志都将显示在Rider/ReSharper测试输出窗口中。
请阅读:docs.microsoft.com/en-us/ef/core/miscellands/logging
应用程序不要为每个上下文实例创建一个新的ILoggerFactory实例,这一点非常重要。这样做将导致内存泄漏和性能不佳。1
如果您想要记录到静态决策(例如控制台),ILJA的答案是可行的,但是如果您想要首先记录到自定义缓冲区,当每个dbContext将日志消息收集到自己的缓冲区时(这是您在多用户服务中想要做的),那么UPSSS-内存泄漏(并且每个几乎为空的模型的内存泄漏大约为20 mb)。。。
当EF6提供了在一行中订阅日志事件的简单解决方案时,现在以如下方式注入日志记录:
var messages = new List<string>();
Action<string> verbose = (text) => {
messages.Add(text);
}; // add logging message to buffer
using (var dbContext = new MyDbContext(BuildOptionsBuilder(connectionString, inMemory), verbose))
{
//..
};
你应该写那集水怪兽。
附注。有人告诉Ef Core架构师,他们对DI和那些他们称之为“容器”的花哨的服务定位器以及他们从ASP.Core借用的流畅的UseXXX有错误的理解。Core不能取代“来自Constructor的粗俗的DI”!至少日志函数通常应该可以通过构造函数注入。
*P.P.S。请同时阅读https://github.com/aspnet/entityframeworkcore/issues/10420。这意味着添加LoggerFactory中断了对InMemory数据提供程序的访问。这实际上是一个抽象泄漏。EF Core在架构方面存在问题。
ILoggerFactory池代码:
public class StatefullLoggerFactoryPool
{
public static readonly StatefullLoggerFactoryPool Instance = new StatefullLoggerFactoryPool(()=> new StatefullLoggerFactory());
private readonly Func<StatefullLoggerFactory> construct;
private readonly ConcurrentBag<StatefullLoggerFactory> bag = new ConcurrentBag<StatefullLoggerFactory>();
private StatefullLoggerFactoryPool(Func<StatefullLoggerFactory> construct) =>
this.construct = construct;
public StatefullLoggerFactory Get(Action<string> verbose, LoggerProviderConfiguration loggerProviderConfiguration)
{
if (!bag.TryTake(out StatefullLoggerFactory statefullLoggerFactory))
statefullLoggerFactory = construct();
statefullLoggerFactory.LoggerProvider.Set(verbose, loggerProviderConfiguration);
return statefullLoggerFactory;
}
public void Return(StatefullLoggerFactory statefullLoggerFactory)
{
statefullLoggerFactory.LoggerProvider.Set(null, null);
bag.Add(statefullLoggerFactory);
}
}
public class StatefullLoggerFactory : LoggerFactory
{
public readonly StatefullLoggerProvider LoggerProvider;
internal StatefullLoggerFactory() : this(new StatefullLoggerProvider()){}
private StatefullLoggerFactory(StatefullLoggerProvider loggerProvider) : base(new[] { loggerProvider }) =>
LoggerProvider = loggerProvider;
}
public class StatefullLoggerProvider : ILoggerProvider
{
internal LoggerProviderConfiguration loggerProviderConfiguration;
internal Action<string> verbose;
internal StatefullLoggerProvider() {}
internal void Set(Action<string> verbose, LoggerProviderConfiguration loggerProviderConfiguration)
{
this.verbose = verbose;
this.loggerProviderConfiguration = loggerProviderConfiguration;
}
public ILogger CreateLogger(string categoryName) =>
new Logger(categoryName, this);
void IDisposable.Dispose(){}
}
public class MyDbContext : DbContext
{
readonly Action<DbContextOptionsBuilder> buildOptionsBuilder;
readonly Action<string> verbose;
public MyDbContext(Action<DbContextOptionsBuilder> buildOptionsBuilder, Action<string> verbose=null): base()
{
this.buildOptionsBuilder = buildOptionsBuilder;
this.verbose = verbose;
}
private Action returnLoggerFactory;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (verbose != null)
{
var loggerFactory = StatefullLoggerFactoryPool.Instance.Get(verbose, new LoggerProviderConfiguration { Enabled = true, CommandBuilderOnly = false });
returnLoggerFactory = () => StatefullLoggerFactoryPool.Instance.Return(loggerFactory);
optionsBuilder.UseLoggerFactory(loggerFactory);
}
buildOptionsBuilder(optionsBuilder);
}
// NOTE: not threadsafe way of disposing
public override void Dispose()
{
returnLoggerFactory?.Invoke();
returnLoggerFactory = null;
base.Dispose();
}
}
private static Action<DbContextOptionsBuilder> BuildOptionsBuilder(string connectionString, bool inMemory)
{
return (optionsBuilder) =>
{
if (inMemory)
optionsBuilder.UseInMemoryDatabase(
"EfCore_NETFramework_Sandbox"
);
else
//Assembly.GetAssembly(typeof(Program))
optionsBuilder.UseSqlServer(
connectionString,
sqlServerDbContextOptionsBuilder => sqlServerDbContextOptionsBuilder.MigrationsAssembly("EfCore.NETFramework.Sandbox")
);
};
}
class Logger : ILogger
{
readonly string categoryName;
readonly StatefullLoggerProvider statefullLoggerProvider;
public Logger(string categoryName, StatefullLoggerProvider statefullLoggerProvider)
{
this.categoryName = categoryName;
this.statefullLoggerProvider = statefullLoggerProvider;
}
public IDisposable BeginScope<TState>(TState state) =>
null;
public bool IsEnabled(LogLevel logLevel) =>
statefullLoggerProvider?.verbose != null;
static readonly List<string> events = new List<string> {
"Microsoft.EntityFrameworkCore.Database.Connection.ConnectionClosing",
"Microsoft.EntityFrameworkCore.Database.Connection.ConnectionClosed",
"Microsoft.EntityFrameworkCore.Database.Command.DataReaderDisposing",
"Microsoft.EntityFrameworkCore.Database.Connection.ConnectionOpened",
"Microsoft.EntityFrameworkCore.Database.Connection.ConnectionOpening",
"Microsoft.EntityFrameworkCore.Infrastructure.ServiceProviderCreated",
"Microsoft.EntityFrameworkCore.Infrastructure.ContextInitialized"
};
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (statefullLoggerProvider?.verbose != null)
{
if (!statefullLoggerProvider.loggerProviderConfiguration.CommandBuilderOnly ||
(statefullLoggerProvider.loggerProviderConfiguration.CommandBuilderOnly && events.Contains(eventId.Name) ))
{
var text = formatter(state, exception);
statefullLoggerProvider.verbose($"MESSAGE; categoryName={categoryName} eventId={eventId} logLevel={logLevel}" + Environment.NewLine + text);
}
}
}
}
非常简单,安装这个Nuget包=>;Microsoft.extensions.logging.console(右键单击您的项目=>Manage Nuget packages=>然后查找它)(或在此链接https://www.Nuget.org/packages/microsoft.extensions.logging.console/)然后重新生成项目//然后您的db上下文必须如下所示=>;
public class Db : DbContext
{
public readonly ILoggerFactory MyLoggerFactory;
public Db()
{
MyLoggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(); });
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseLoggerFactory(MyLoggerFactory);
}
}