c# - 如何将自定义日志记录连接到我的 ef6 迁移?
问题描述
我有一个看起来像这样的 DbMigrationsConfiguration:
internal sealed class Configuration : DbMigrationsConfiguration<DatabaseProject.DB>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
AutomaticMigrationDataLossAllowed = false;
}
}
在其他地方,在我的 DbContext 类中,我有:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DB, DbProject.Migrations.Configuration>(useSuppliedContext: true));
// and so on...
我想在应用迁移时使用 MigrationsLogger 记录一些信息。所以我使用 serilog 设置了一个像这样的简单类:
public class EfLogger : MigrationsLogger
{
public override void Info(string message)
{
Log.Logger.Information("Machine {name} reported EF Migration Message: {message}", Environment.MachineName,
message);
}
public override void Warning(string message)
{
Log.Logger.Warning("Machine {name} reported EF Migration Warning: {message}", Environment.MachineName,
message);
}
public override void Verbose(string message)
{
Log.Logger.Verbose("Machine {name} reported EF Migration verbose message: {message}", Environment.MachineName,
message);
}
}
那么如何更改我的配置以使用新的记录器?我在任何地方都找不到任何示例或文档。
解决方案
我研究了它是如何工作的,我认为你将无法MigrateDatabaseToLatestVersion
直接使用。不过,您应该能够覆盖它。如果您查看那里的实际逻辑,它实际上非常简单:
https://github.com/dotnet/ef6/blob/master/src/EntityFramework/MigrateDatabaseToLatestVersion%60.cs
public virtual void InitializeDatabase(TContext context)
{
Check.NotNull(context, "context");
var migrator = new DbMigrator(_config, _useSuppliedContext ? context : null);
migrator.Update();
}
要将日志添加到其中,请创建一个MigrateDatabaseToLatestVersionWithLogging
继承自标准的新实现MigrateDatabaseToLatestVersion
,然后覆盖该方法并在调用 update 之前引入日志装饰器。像这样的东西(未经测试):
public override void InitializeDatabase(TContext context)
{
_ = context ?? throw new ArgumentNullException(nameof(context));
var migrator = new MigratorLoggingDecorator(
new DbMigrator(_config, _useSuppliedContext ? context : null),
new EfLogger());
migrator.Update();
}
推荐阅读
- c# - C# HttpClient 请求 HTTPS 异常错误
- android - Android Volley StringRequest 有时会提供空婴儿车
- javascript - 如何从一个网页播放音乐并从另一个网页停止
- python - pyplot,为什么不显示 x 轴?
- reactjs - 反应,风格与 if inside
- pandas - 使用 Pandas 在每个 PeriodIndex 中选择最旧的行
- python - 如何使用python获取行簇
- angularjs - 为什么按钮事件在第三次点击后停止?
- python - 使用 Python 将具有未知列的 CSV 导入 PostgreSQL
- pandas - 如何在熊猫中根据条件分组