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

# 監控資料庫交易的執行時間

> 說明如何使用 Laravel 13 的 Connection::whenTransactionRunsLongerThan，在提交或回滾時偵測長時間執行的交易。

調查交易延遲時，除了 SQL 的執行時間，也需要確認交易內執行的應用程式程式碼以及資料庫的鎖定等待時間。Laravel 13.x 的 `Connection::whenTransactionRunsLongerThan` 會在交易整體的經過時間超過指定門檻時呼叫 callback。

> [!NOTE]
>
> 本頁以 [Laravel Framework 13.x 的實作](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Connection.php) 為基礎。請確認你使用的 Framework 版本包含此方法。

## 註冊 callback

若要監控整個應用程式的資料庫連線，請在 service provider 的 `boot` 方法中註冊。門檻的單位是 **毫秒**。

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

namespace App\Providers;

use Illuminate\Database\Connection;
use Illuminate\Database\Events\TransactionCommitted;
use Illuminate\Database\Events\TransactionRolledBack;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        DB::connection()->whenTransactionRunsLongerThan(
            500,
            function (
                Connection $connection,
                TransactionCommitted|TransactionRolledBack $event,
                float $duration,
            ): void {
                Log::warning('Long database transaction detected.', [
                    'connection' => $connection->getName(),
                    'duration_ms' => $duration,
                    'event' => $event::class,
                ]);
            },
        );
    }
}
```

callback 會收到以下 3 個參數。

* `Connection`: 受監控的資料庫連線
* `TransactionCommitted|TransactionRolledBack`: 表示交易是 commit 還是 rollback 的 event
* `float`: 量測到的經過時間（毫秒）

像 `DB::connection('mysql')` 這樣指定連線名稱，就能只監控特定連線。若要監控多個連線，請在各個 `Connection` 上分別註冊 callback。

## 量測範圍

量測在外層交易開始時開始，並在外層交易 commit 或 rollback 時結束。

```php theme={null}
DB::transaction(function () {
    // 從這裡開始量測

    Order::create($orderData);

    DB::transaction(function () {
        // 內層 transaction 不會個別量測
        Inventory::reserve($product);
    });

    // 在這裡結束量測，若超過門檻就會呼叫 callback
});
```

Laravel 只會在 transaction level 從 `0` 變成 `1` 時保存開始時間。因此，即使內層 transaction 以 savepoint 方式運作，內層的處理時間也會計入外層交易的經過時間。這並不是以獨立門檻監控內層 transaction 的機制。

callback 會在 transaction level 回到 `0` 之後呼叫。即使 `DB::transaction` 的 callback 拋出例外並 rollback，也能收到 `TransactionRolledBack` event 與量測時間。手動呼叫 `beginTransaction` / `commit` / `rollBack` 時也會觸發相同的 event。

## 門檻的指定方式

`whenTransactionRunsLongerThan` 的第 1 個參數可以傳入以下形式。

| 值 | 意義 |
| - | - |
| `int` 或 `float` | 毫秒 |
| `CarbonInterval` | interval 的總毫秒數 |
| `DateTimeInterface` | 到指定時間為止的秒數換算成毫秒的值 |

通常直接指定毫秒就足夠了。若想以時間單位表示，可以使用 `CarbonInterval`。

```php theme={null}
use Carbon\CarbonInterval;
use Illuminate\Support\Facades\DB;

DB::connection()->whenTransactionRunsLongerThan(
    CarbonInterval::seconds(1),
    static function (): void {
        // 記錄監控用的日誌或 metrics
    },
);
```

判斷依據是「經過時間是否大於門檻」。經過時間與門檻相同時不會呼叫 callback。將門檻設為 `0` 時，所有量測到的 transaction 都會觸發 callback。

## 與 SQL 延遲區分

Laravel 也提供 `whenQueryingForLongerThan`，用來監控單一 request 內執行之 SQL 的累計時間。兩個 API 的量測對象不同。

| API | 量測對象 | callback 的 event |
| - | - | - |
| `whenQueryingForLongerThan` | request 內 SQL 執行時間的累計 | `QueryExecuted` |
| `whenTransactionRunsLongerThan` | 從外層 transaction 開始到 commit 或 rollback 的經過時間 | `TransactionCommitted` 或 `TransactionRolledBack` |

若在交易內呼叫外部 API 或發生鎖定等待，交易的經過時間可能會大於 SQL 的累計時間。同時記錄兩者，就更容易區分延遲是來自 SQL 本身，還是交易內的其他處理。

## 維運時的注意事項

callback 會在 commit 或 rollback 的處理過程中呼叫，因此請僅用於監控。可以輸出日誌或記錄 metrics，但不要在同一連線上執行額外的更新，也不要進行耗時的外部通訊。

此外，在交易內呼叫外部 API 時，其等待時間也會被量測。評估能否將外部通訊移到交易之外，不僅能減少通知，也能縮短鎖定的持有時間。

## 參考的一手資料

* [Laravel 官方資料庫文件](https://github.com/laravel/docs/blob/13.x/database.md)
* [`Connection::whenTransactionRunsLongerThan` 的實作](https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Connection.php)
* [加入 Laravel Framework 的提交](https://github.com/laravel/framework/commit/5edfeeed86961983042d0bdbbe7265d5b6dc7bba)


## Related topics

- [進階主題](https://kawax.biz/zh-TW/advanced/index.md)
- [Pipeline 模式](https://kawax.biz/zh-TW/advanced/pipeline.md)
- [Eloquent Observer 與模型事件](https://kawax.biz/zh-TW/advanced/eloquent-observers.md)
- [使用 MigrationFailed 事件處理遷移失敗](https://kawax.biz/zh-TW/advanced/migration-failed-event.md)
- [套件的資料庫連線擴充](https://kawax.biz/zh-TW/advanced/package-database-connections.md)


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