Logan Bailey

Adventures In Web Development

Blog, About, GitHub, and LinkedIn

Often times when it comes to logging, you want to log everything. However as your application grows this can become more and more expensive. This is where the Fingers Crossed Handler comes in handy. The Fingers Crossed Handler allows you to set a minimum log threshold, no logs will be written unless a log of the given threshold or higher has been given. This assumes you only want all your logs if an errors occurs at which point you'll want to know as much as you can.

The Fingers Crossed Handler is fairly easy to setup:

use Monolog\Handler\StreamHandler;
use Monolog\Handler\FingersCrossedHandler;
use Monolog\Logger;

$printer = new StreamHandler(STDOUT);
$fingers = new FingersCrossedHandler($printer, new ErrorLevelActivationStrategy(Logger::ERROR));

$logger = new Logger('Demo', [$fingers]);

Yesterday, while watching our logs as I ran a deploy. I noticed a flaw with our usage of the Fingers Crossed Handler. We had logs that were informational and did require seeing the full dump of all logs during the request. One of these in particular read "Client Acme does not have feature enabled, using fallback". It's nice to know the client is using the fall back, but since we use finger crossed I also see all of debug logs. We needed a way for some logs to trigger a dump of all logs, while some logs would just be logged. An error would show all logs, while info would show that one log. While digging into the code, I found that 4 years ago Monolog added this exact functionality.

$fingers = new Monolog\Handler\FingersCrossedHandler(
    $printer,
    new ErrorLevelActivationStrategy(Logger::ERROR),
    0,
    true,
    true,
    Logger::WARNING
);

The addition is this "new" last parameter, Logger::WARNING. This is the minimum level at which an entry should be flushed, though not the entire buffer. With the setup I have, all WARNING level or high logs will be flushed but logs lower than WARNING will only appear if there's an ERROR or higher level log.

Posted In:
logging monolog php