> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# 使用 MigrationEnded 事件测量迁移时间

> 讲解如何从 Laravel 13 的 MigrationEnded 事件获取迁移的执行时间，并将其用于监控和测试。

如果要记录迁移的执行时间，请监听 `Illuminate\Database\Events\MigrationEnded`。在 Laravel 13.x 中，成功执行的单个迁移的 `up` 或 `down` 方法所花费的时间会作为 `duration` 传递。

## 事件包含的信息

`MigrationEnded` 继承自 `MigrationEvent`，公开目标迁移和执行结果。

| 属性 | 类型 | 内容 |
| - | - | - |
| `migration` | `Migration` | 已执行的迁移实例 |
| `method` | `string` | 被调用的方法，`up` 或 `down` |
| `name` | `string\|null` | 迁移名称。根据执行路径可能为 `null` |
| `duration` | `float\|null` | `up` / `down` 的执行时间，单位为毫秒 |

在常规的迁移执行中，`duration` 是四舍五入到小数点后两位的 `float`。在自行创建事件等情况下它可能为 `null`，因此监控处理应先检查该值再使用。

## 将执行时间记录到日志

在应用的服务提供者中监听事件，并将数据作为结构化上下文传递给日志。

```php theme={null}
<?php

namespace App\Providers;

use Illuminate\Database\Events\MigrationEnded;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Event::listen(MigrationEnded::class, function (MigrationEnded $event): void {
            Log::info('Database migration finished.', [
                'migration' => $event->name ?? $event->migration::class,
                'class' => $event->migration::class,
                'method' => $event->method,
                'duration_ms' => $event->duration,
            ]);
        });
    }
}
```

即使能够获取 `name`，同时记录 `migration::class` 也能在匿名类等执行路径不同的情况下更容易识别目标。`duration_ms` 已经是毫秒，因此无需转换为其他单位即可发送到日志或指标。

## 事件的触发顺序

只有在 `up` 或 `down` 执行成功时，Laravel 才会触发 `MigrationEnded`。

```mermaid theme={null}
flowchart TD
    A["触发 MigrationStarted"] --> B["开始计时"]
    B --> C["执行迁移的 up / down"]
    C -->|成功| D["转换为毫秒并计算 duration"]
    D --> E["触发 MigrationEnded"]
    C -->|异常| F["触发 MigrationFailed"]
    F --> G["重新抛出原始异常"]
```

失败的迁移不会触发 `MigrationEnded`。如 [使用 MigrationFailed 事件处理迁移失败](https://kawax.biz/zh-CN/advanced/migration-failed-event.md) 中所述，请将记录失败原因和异常的处理分离到 `MigrationFailed` 的监听器中。

## 测量的内容

框架在调用迁移方法之前使用 `microtime(true)` 开始计时，并在 `up` 或 `down` 执行后立即结束。因此，以下处理包含在测量范围内：

* 迁移方法中的 PHP 代码
* 从该方法执行的数据库查询
* 查询执行期间数据库的等待时间

另一方面，`MigrationStarted` 的监听器、`MigrationEnded` 的监听器以及整个迁移批次的处理时间不包含在内。即使使用了 schema 事务，计时也是在事务的 callback 内部进行的，因此请与事务的开始、commit 等周边处理区分开来。

这个值并不表示整个 `php artisan migrate` 命令或包含多个迁移的整个批次的时间。请将其用作比较各个 `up` / `down` 中时间花在哪里的值。

## 通知超过阈值的迁移

只将超过一定时间的迁移记录为警告，就能在不增加常规日志的情况下发现缓慢的变更。

```php theme={null}
use Illuminate\Database\Events\MigrationEnded;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;

Event::listen(MigrationEnded::class, function (MigrationEnded $event): void {
    if ($event->duration === null || $event->duration <= 1000) {
        return;
    }

    Log::warning('Slow database migration detected.', [
        'migration' => $event->name ?? $event->migration::class,
        'method' => $event->method,
        'duration_ms' => $event->duration,
    ]);
});
```

请根据应用的数据量和部署流程决定阈值。不要仅凭时间判定为失败，而应将其作为与 `MigrationFailed` 的异常信息分开的"延迟"指标来处理。

## 在测试中检查执行时间

使用 `Event::fake` 和 `Event::assertDispatched`，可以在不运行实际事件监听器的情况下验证 `duration` 的格式。

```php theme={null}
<?php

namespace Tests\Feature;

use Illuminate\Database\Events\MigrationEnded;
use Illuminate\Support\Facades\Event;
use Tests\TestCase;

class MigrationDurationTest extends TestCase
{
    public function test_migration_ended_contains_duration(): void
    {
        Event::fake([MigrationEnded::class]);

        $this->artisan('migrate', [
            '--path' => 'tests/Fixtures/migrations',
        ])->assertSuccessful();

        Event::assertDispatched(MigrationEnded::class, function (MigrationEnded $event): bool {
            return $event->method === 'up'
                && is_float($event->duration)
                && $event->duration >= 0;
        });
    }
}
```

如果也要监控 `down` 的执行时间，请运行 `migrate:rollback`，并以同样的方式验证 `method === 'down'` 的事件。时间长短受执行环境和数据库状态影响，因此测试中应检查类型以及值不为负数，而不是特定的毫秒值。

## 总结

* `MigrationEnded` 的 `duration` 以毫秒表示成功执行的单个迁移的 `up` / `down` 执行时间。
* 可以将执行时间发送到日志或指标，用于发现缓慢的迁移。
* 不包含事件监听器和整个批次的时间，因此应与整个命令的性能测量分开考虑。
* 划分监控职责：失败由 `MigrationFailed` 处理，成功执行的延迟由 `MigrationEnded` 处理。

## 参考的一手资料

* [Laravel 官方文档：迁移事件](https://github.com/laravel/docs/blob/13.x/migrations.md#events)
* [Framework 13.x: MigrationEnded](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Events/MigrationEnded.php)
* [Framework 13.x: Migrator 的事件触发与计时](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Migrations/Migrator.php)
* [Framework 13.x: 迁移事件的测试](https://github.com/laravel/framework/blob/13.x/tests/Integration/Database/MigratorEventsTest.php)


## Related topics

- [使用 MigrationFailed 事件处理迁移失败](https://kawax.biz/zh-CN/advanced/migration-failed-event.md)
- [进阶主题](https://kawax.biz/zh-CN/advanced/index.md)
- [数据库迁移](https://kawax.biz/zh-CN/migrations.md)
- [包迁移的发布与更新](https://kawax.biz/zh-CN/advanced/package-migrations.md)
- [進階主題](https://kawax.biz/zh-TW/advanced/index.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.