如何在 C# 中做一个时间记录器 class 包装器

How to do a time logger class wrapper in C#

我有很多(大约一千个)FluentMigrator Migration classes 在我们的构建服务器上开始超时。

对于那些没有使用过 FluentMigrator 的人 - 迁移的工作方式是您的所有迁移都继承自 Migration class,其中包含 Up()Down() 运行 SQL 数据库迁移脚本的方法 - 简单易行。

现在很懒,我引入了一个 LoggingMigration class 来记录迁移开始的时间 运行ning(并简单地将 : Migration 替换为 : LoggingMigration在那个项目的 VS 中)。

public class LoggingMigration : Migration
{
    public DateTime StartTime { get; private set; }

    public LoggingMigration()
    {
        this.StartTime = DateTime.Now;
        Console.WriteLine("Start {0} - TIME: {1:yyyy-MM-dd HH:mm:ss.fff}", this.GetType().Name, StartTime);
    }

    public override void Up()
    {
    }

    public override void Down()
    {
    }
}

我还想记录下迁移的时间运行 以便更轻松地了解哪些迁移需要很长时间。

我正在考虑使用像这样的析构函数:

    ~LoggingMigration()
    {
        Console.WriteLine("End(?) {0} - TIME: {1}", this.GetType().Name, DateTime.Now.Subtract(StartTime));
    }

但事情只是 volatile and unpredictable

如何在子 class 中的 Up() 方法完成后添加 运行 的机制? 或者其他一些方法可以完成这项工作?

如何覆盖受保护的方法而不是 public 方法:

public abstract class Migration
{
    // ...

    protected DateTime StartTime { get; private set; }

    public Migration()
    {
        this.StartTime = DateTime.Now;
        Console.WriteLine("Start {0} - TIME: {1:yyyy-MM-dd HH:mm:ss.fff}", this.GetType().Name, StartTime);
    }

    public void Up()
    {
        OverrideUp();
        Console.WriteLine("End(?) {0} - TIME: {1}", this.GetType().Name, DateTime.Now.Substracts(StartTime));
    }

    public void Down()
    {
        // ...
        OverrideDown();
    }

    protected abstract void OverrideUp();
    protected abstract void OverrideDown();
}

为迁移创建装饰器class。 它看起来像:

public class LoggingMigrationDecorator : Migration {
        private Migration _migrationClass;
        public DateTime StartTime { get; private set; }

        public LoggingMigrationDecorator (Migration toDecorate)
                {
                     _migrationClass = toDecorate;
                    this.StartTime = DateTime.Now;
                    Console.WriteLine("Start {0} - TIME: {1:yyyy-MM-dd HH:mm:ss.fff}", this.GetType().Name, StartTime);
                }

                public override void Up()
                {
                 toDecorate.Up();
                 stopTimerFunction(); // your function that will stop timer and do something with result

                }



      public override void Down()
            {
            }
        }
    }

装饰器模式示例: http://www.dofactory.com/net/decorator-design-pattern