> ## 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-TW/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-TW/advanced/migration-failed-event.md)
- [進階主題](https://kawax.biz/zh-TW/advanced/index.md)
- [資料庫遷移（Migrations）](https://kawax.biz/zh-TW/migrations.md)
- [事件](https://kawax.biz/zh-TW/packages/laravel-copilot-sdk/events.md)
- [进阶主题](https://kawax.biz/zh-CN/advanced/index.md)


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