Skip to content
Documentation

Logging behavior

Log method calls, results and failures with one attribute. A #[Loggable] behavior with a PSR-3 logger that keeps logging code and logger dependencies out of your domain classes.

A customer says a withdrawal failed, and nobody can tell why. The answer should be in the logs, but logging every important method by hand buries the business logic. This page moves logging into a behavior: you mark a method with #[Loggable], and the framework runs the logging as middleware around it. The words behavior class, behavior and matching rule are explained in the terms table.

A bank account with two operations:

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;
}
}

A useful log strategy: write one line when a method starts and one when it ends. A start without an end points to the failure, even when the process dies and no catch block runs. Done by hand, it looks like this:

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
}

The logging outweighs the business logic, and it gets worse:

  • The domain class depends on a logger. An account doesn’t need one to hold money. Every constructor call and every test now passes one in.
  • The same block is copied into every important method. The copies drift apart: different messages, different context keys, a forgotten failure branch.
  • Secrets leak. A copy that logs all arguments logs the PIN as well.

Logging goes into one behavior class. The methods that need it are marked with an attribute.

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

A plain marker, with no dependency on the framework. It can go on a method, or on a class (see Log a whole class).

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;
}
}

The logger dependency is gone, and the attribute still tells every reader that these calls are logged. withdraw() now takes a PIN, marked with PHP’s own #[\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] wraps the method, and @execution(App\Attribute\Loggable) selects every method that carries the attribute. Inside:

  • (string) $invocation names the call, for example execution(App\Bank\Account->withdraw()).
  • arguments() pairs each argument with its parameter name and hides parameters marked #[\SensitiveParameter]. It is a private helper without a behavior attribute, so it is not a behavior itself.
  • proceed() runs the original method. A failure is logged and thrown again, so callers see exactly the exception they saw before. The behavior catches \Throwable, so errors are logged too, not only exceptions.
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)),
);
}
}

Any PSR-3 logger works, Monolog included. The logger comes from your application container once it is attached with setDelegate() (see Dependencies). With the Symfony, Laravel or Yii3 bridge, the behavior class is an autowired service and this step disappears (Integrations).

$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]"}
  • Domain classes stay clean. No logger in the constructor, no try/catch for logging, and tests construct the class as before.
  • One format everywhere. Messages, context keys and the failure branch are written once, in LoggingAspect.
  • Secrets stay out. The PIN never reaches the logger.
  • It works on any method. Private, final and static methods of compiled classes can be logged too; see Intercept anything.

When every public method of a class should be logged, put the attribute on the class and extend the rule:

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) alone selects every member of the marked class, properties included. The second half, execution(public **->*(*)), narrows it to public methods. More combinations are in Matching rules.

  • Only failures. An #[AfterThrowing] behavior receives the exception and runs only when the method throws. See AfterThrowing.
  • Timing. Measure hrtime(true) around proceed() and log the duration, as in the behavior class example.
  • Log levels per method. Give the attribute a property, for example #[Loggable(level: LogLevel::DEBUG)], and read it with $invocation->getMethod()->getAttributes(Loggable::class), as the caching behavior reads its lifetime.

© 2026 Alexander Lisachenko