Using PSR-3 placeholders properly

Submitted by Larry on 26 February 2023 - 10:26am

In the last 2 years or so, I've run into a number of projects that claim to use the PSR-3 logging standard as published by the PHP Framework Interoperability Group (PHP-FIG, or just FIG). Unfortunately, it's quite clear that those responsible for the project have not understood PSR-3 and how it is intended to work. This frustrates me greatly, as PSR-3's design addresses a number of issues that these projects are not benefiting from, and it reduces interoperability between projects (which was the whole point in the first place).

Rather than just rant angrily online (fun as it is, it doesn't actually accomplish anything), many of my PHP community colleagues encouraged me to blog about using PSR-3 properly. So, here we are.

The Short, Short version

If you just want the final point, here it is.

If you're writing this:

$logger->info("User $userId bought $productName");

Then you're doing it wrong, abusing PSR-3, and may have a security attack vector. You need to switch to doing this instead:

$logger->info("User {userId} bought {productName}", [
   'userId' => $userId,
   'productName' => $productName,
]);

And if your logger isn't handling that properly, it means you have it misconfigured and need to fix your configuration.

If your project's documentation is telling you to do the first one, then your project's documentation is wrong, and it should be fixed.

If you want to understand why, read on.

Continue reading this post on PeakD.