ロギングの振る舞い
メソッドの呼び出し、結果、失敗を属性 1 つでログに記録します。PSR-3 ロガーを使う #[Loggable] の behavior は、ロギングのコードもロガーへの依存もドメインクラスの外に置きます。
このページは英語版からの翻訳です。基準となるのは英語版のページです。 原文を読む
顧客から、出金に失敗したと連絡がありました。しかし理由は誰にもわかりません。答えはログにあるはずですが、重要なメソッドのすべてに手作業でログ出力を書けば、ビジネスロジックが埋もれてしまいます。このページでは、ロギングを behavior(振る舞い)に移します。メソッドに #[Loggable] を付けると、フレームワークがロギングをそのメソッドの周りで middleware(ミドルウェア)として実行します。behavior class(振る舞いクラス)、behavior、matching rule(マッチングルール)という言葉は用語表で説明しています。
2 つの操作を持つ銀行口座です。
final class Account{ public function __construct(private int $balance = 0) {}
public function deposit(int $amount): void { $this->balance += $amount; }
public function withdraw(int $amount): void { if ($amount > $this->balance) { throw new InsufficientFunds($this->balance, $amount); } $this->balance -= $amount; }}役に立つログの方針は、メソッドの開始時に 1 行、終了時に 1 行を書くことです。開始だけがあって終了がなければ、そこが失敗箇所です。プロセスが落ちて catch ブロックが実行されなかった場合でもわかります。手作業で書くと次のようになります。
use Psr\Log\LoggerInterface;
final class Account{ public function __construct( private LoggerInterface $logger, private int $balance = 0, ) {}
public function withdraw(int $amount): void { $this->logger->info('Entering withdraw', ['amount' => $amount]); try { if ($amount > $this->balance) { throw new InsufficientFunds($this->balance, $amount); } $this->balance -= $amount; $this->logger->info('Finished withdraw', ['amount' => $amount]); } catch (\Throwable $exception) { $this->logger->error('Failed withdraw', ['exception' => $exception]); throw $exception; } }
// deposit(): the same wrapper again}ロギングがビジネスロジックを上回る分量になり、事態はさらに悪くなります。
- ドメインクラスがロガーに依存する。 口座がお金を保持するのにロガーは要りません。それなのに、コンストラクターの呼び出しのたび、テストのたびにロガーを渡すことになります。
- 同じブロックが重要なメソッドのすべてにコピーされる。 コピーは少しずつずれていきます。メッセージが違い、コンテキストのキーが違い、失敗時の分岐が抜け落ちます。
- 秘密情報が漏れる。 すべての引数をログに出すコピーは、PIN までログに出します。
ロギングの behavior
Section titled “ロギングの behavior”ロギングは 1 つの behavior class にまとめます。それを必要とするメソッドには属性で目印を付けます。
namespace App\Attribute;
use Attribute;
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)]final readonly class Loggable {}フレームワークに依存しない、ただの目印です。メソッドにもクラスにも付けられます(クラス全体をログに記録するを参照)。
2. メソッドに目印を付ける
Section titled “2. メソッドに目印を付ける”use App\Attribute\Loggable;
final class Account{ public function __construct(private int $balance = 0) {}
#[Loggable] public function deposit(int $amount): void { $this->balance += $amount; }
#[Loggable] public function withdraw(int $amount, #[\SensitiveParameter] string $pin): void { if ($amount > $this->balance) { throw new InsufficientFunds($this->balance, $amount); } $this->balance -= $amount; }}ロガーへの依存はなくなり、それでいて属性が、これらの呼び出しがログに記録されることをコードを読む人すべてに伝えます。withdraw() は PIN を受け取るようになり、その引数には PHP 自身の #[\SensitiveParameter] を付けています。
3. behavior class
Section titled “3. behavior class”namespace App\Aspect;
use Go\Aop\Aspect;use Go\Aop\Intercept\MethodInvocation;use Go\Lang\Attribute\Around;use Psr\Log\LoggerInterface;
final class LoggingAspect implements Aspect{ public function __construct(private readonly LoggerInterface $logger) {}
#[Around('@execution(App\Attribute\Loggable)')] public function log(MethodInvocation $invocation): mixed { $context = ['method' => (string) $invocation, 'arguments' => $this->arguments($invocation)]; $this->logger->info('Entering {method}', $context);
try { $result = $invocation->proceed(); $this->logger->info('Finished {method}', $context);
return $result; } catch (\Throwable $exception) { $this->logger->error('Failed {method}: {message}', $context + [ 'message' => $exception->getMessage(), 'exception' => $exception, ]);
throw $exception; } }
/** @return array<string, mixed> */ private function arguments(MethodInvocation $invocation): array { $values = $invocation->getArguments(); $named = []; foreach ($invocation->getMethod()->getParameters() as $i => $parameter) { $hidden = $parameter->getAttributes(\SensitiveParameter::class) !== []; $named[$parameter->name] = $hidden ? '[hidden]' : ($values[$i] ?? null); }
return $named; }}#[Around] がメソッドを包み、@execution(App\Attribute\Loggable) がこの属性を持つすべてのメソッドを選びます。中身は次のとおりです。
(string) $invocationは呼び出しの名前を表します。たとえばexecution(App\Bank\Account->withdraw())です。arguments()は各引数をそのパラメーター名と対応付け、#[\SensitiveParameter]が付いたパラメーターを隠します。これは behavior の属性を持たない private なヘルパーなので、それ自体は behavior ではありません。proceed()は元のメソッドを実行します。失敗はログに記録されてから再びスローされるので、呼び出し元には以前とまったく同じ例外が届きます。behavior は\Throwableを捕捉するので、例外だけでなくエラーもログに記録されます。
4. behavior class を登録する
Section titled “4. behavior class を登録する”use App\Aspect\LoggingAspect;use Go\Core\AspectContainer;use Go\Core\AspectKernel;use Psr\Log\LoggerInterface;
final class AppKernel extends AspectKernel{ protected function configureAop(AspectContainer $container): void { $container->addLazyService( LoggingAspect::class, static fn(AspectContainer $c) => new LoggingAspect($c->getService(LoggerInterface::class)), ); }}Monolog を含め、PSR-3 のロガーなら何でも使えます。ロガーは、setDelegate() で接続したアプリケーションのコンテナから取得します(依存関係を参照)。Symfony、Laravel、Yii3 のブリッジを使う場合、behavior class はオートワイヤリングされるサービスになり、このステップはなくなります(インテグレーション)。
得られるもの
Section titled “得られるもの”$account = new Account(100);$account->deposit(50);$account->withdraw(500, '1234');[info] Entering execution(App\Bank\Account->deposit()) {"amount":50}[info] Finished execution(App\Bank\Account->deposit()) {"amount":50}[info] Entering execution(App\Bank\Account->withdraw()) {"amount":500,"pin":"[hidden]"}[error] Failed execution(App\Bank\Account->withdraw()): Insufficient funds: balance 150, requested 500 {"amount":500,"pin":"[hidden]"}- ドメインクラスはクリーンなまま。 コンストラクターにロガーはなく、ロギングのための
try/catchもなく、テストではこれまでどおりにクラスを生成できます。 - どこでも同じフォーマット。 メッセージ、コンテキストのキー、失敗時の分岐は、
LoggingAspectに一度だけ書かれています。 - 秘密情報は外に出ない。 PIN がロガーに届くことはありません。
- どんなメソッドにも使える。 コンパイルされたクラスの private メソッド、
finalメソッド、static メソッドもログに記録できます。Intercept anything を参照してください。
クラス全体をログに記録する
Section titled “クラス全体をログに記録する”クラスのすべての public メソッドをログに記録したい場合は、属性をクラスに付けて、ルールを拡張します。
#[Around('@execution(App\Attribute\Loggable) || (@within(App\Attribute\Loggable) && execution(public **->*(*)))')]public function log(MethodInvocation $invocation): mixed#[Loggable]final class Transfers{ public function send(string $to, int $amount): Receipt { /* logged */ }
private function fee(int $amount): int { /* not logged */ }}@within(App\Attribute\Loggable) だけでは、目印を付けたクラスのすべてのメンバーがプロパティも含めて選ばれます。後半の execution(public **->*(*)) が、それを public メソッドに絞り込みます。ほかの組み合わせは matching rule にあります。
バリエーション
Section titled “バリエーション”- 失敗だけを記録する。
#[AfterThrowing]の behavior は例外を受け取り、メソッドが例外を投げたときにだけ実行されます。AfterThrowing を参照してください。 - 処理時間を計る。
proceed()の前後でhrtime(true)を計測し、所要時間をログに記録します。behavior class の例と同じやり方です。 - メソッドごとのログレベル。 属性にプロパティを持たせ(たとえば
#[Loggable(level: LogLevel::DEBUG)])、それを$invocation->getMethod()->getAttributes(Loggable::class)で読み取ります。キャッシュの振る舞いが有効期間を読み取るのと同じ方法です。
© 2026 Alexander Lisachenko
