跳转到内容
文档

日志行为

只需一个注解,就能记录方法调用、结果和失败。基于 PSR-3 logger 的 #[Loggable] behavior,让日志代码和 logger 依赖远离你的领域类。

本页译自英文,以英文页面为准。 阅读原文

一位客户说一笔取款失败了,却没人说得清原因。答案本该在日志里,可是给每个重要方法手写日志,会把业务逻辑淹没。本页把日志移进一个 behavior(行为):你用 #[Loggable] 标记一个方法,框架就会把日志记录作为 middleware(中间件)在它周围运行。behavior class(行为类)、behavior 和 matching rule(匹配规则)这几个词的含义见 术语表。

一个有两种操作的银行账户:

src/Bank/Account.php
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;
}
}

一种实用的日志策略是:方法开始时写一行,结束时再写一行。只有开始没有结束的记录就指向了故障所在,即使进程直接崩溃、任何 catch 块都没有运行也是如此。手工实现的话,是这个样子:

src/Bank/Account.php
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
}

日志代码的分量超过了业务逻辑,而且情况还会更糟:

  • 领域类依赖 logger。 账户存钱并不需要 logger。现在每次调用构造函数、每个测试都得传一个进去。
  • 同一段代码被复制到每个重要方法里。 副本之间逐渐走样:消息不同、上下文键不同、某处忘了处理失败分支。
  • 敏感信息泄露。 一份记录全部参数的副本,会把 PIN 也记下来。

日志逻辑放进一个 behavior class,需要它的方法用一个注解标记。

src/Attribute/Loggable.php
namespace App\Attribute;
use Attribute;
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)]
final readonly class Loggable {}

一个纯粹的标记,不依赖框架。它可以放在方法上,也可以放在类上(见 记录整个类的日志)。

src/Bank/Account.php
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;
}
}

Logger 依赖不见了,而注解依然让每个读代码的人知道这些调用会被记录。withdraw() 现在多了一个 PIN 参数,用 PHP 自带的 #[\SensitiveParameter] 标记。

src/Aspect/LoggingAspect.php
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) 选中所有带这个注解的方法。在 behavior 内部:

  • (string) $invocation 给出调用的名称,例如 execution(App\Bank\Account->withdraw())。
  • arguments() 把每个参数与它的参数名配对,并隐藏标记了 #[\SensitiveParameter] 的参数。它是一个没有 behavior 注解的私有辅助方法,所以它本身不是 behavior。
  • proceed() 运行原始方法。失败会被记录并重新抛出,调用方看到的异常与以前完全相同。Behavior 捕获的是 \Throwable,因此不只是异常,错误也会被记录。
src/AppKernel.php
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)),
);
}
}

任何 PSR-3 logger 都可以,包括 Monolog。logger 来自你的应用容器,前提是已用 setDelegate() 把它挂接上(见 依赖)。如果使用 Symfony、Laravel 或 Yii3 的桥接包,behavior class 就是一个自动装配的服务,这一步也就不需要了(集成)。

$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]"}
  • 领域类保持干净。 构造函数里没有 logger,没有为日志而写的 try/catch,测试照旧构造这个类。
  • 处处统一的格式。 消息、上下文键和失败分支只在 LoggingAspect 里写一次。
  • 敏感信息不会外泄。 PIN 永远不会到达 logger。
  • 适用于任何方法。 编译后的类中的私有方法、final 方法和静态方法也能被记录;见 Intercept anything。

如果一个类的所有 public 方法都要记录日志,就把注解放在类上,并扩展规则:

src/Aspect/LoggingAspect.php
#[Around('@execution(App\Attribute\Loggable) || (@within(App\Attribute\Loggable) && execution(public **->*(*)))')]
public function log(MethodInvocation $invocation): mixed
src/Bank/Transfers.php
#[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 方法。更多组合方式见 匹配规则。

  • 只记录失败。 #[AfterThrowing] behavior 会收到异常,并且只在方法抛出异常时运行。见 AfterThrowing。
  • 计时。 在 proceed() 前后测量 hrtime(true) 并记录耗时,就像 behavior class 示例 中那样。
  • 按方法设置日志级别。 给注解加一个属性,例如 #[Loggable(level: LogLevel::DEBUG)],再用 $invocation->getMethod()->getAttributes(Loggable::class) 读取它,就像 缓存行为 读取过期时间那样。

© 2026 Alexander Lisachenko