首页 > 解决方案 > 如何将自定义日志记录连接到我的 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);
        }
    }

那么如何更改我的配置以使用新的记录器?我在任何地方都找不到任何示例或文档。

标签: c#loggingentity-framework-6serilog

解决方案


我研究了它是如何工作的,我认为你将无法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 之前引入日志装饰器。像这样的东西(未经测试):

https://docs.microsoft.com/en-us/dotnet/api/system.data.entity.migrations.infrastructure.migratorloggingdecorator?view=entity-framework-6.2.0

    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();
    }

推荐阅读