From b2644b4b1b74aeebebf5411e82ea8867d0c8ed92 Mon Sep 17 00:00:00 2001 From: Bart Jaskulski <bjaskulski@protonmail.com> Date: Sat, 20 Jul 2024 03:41:57 +0200 Subject: [PATCH] feat: integrate FingersCrossedHandler In situation, when we don't collect verbose logs, but we still may be interested in any errors occurring on client's website and being able to investigate those after gaining access, we may make use of `action_level` option in `SimpleLoggerFactory`. With this option set to some level, we configure `FingersCrossedHandler` which will ensure, when action level is hit, all log stack is persisted. Signed-off-by: Bart Jaskulski <bjaskulski@protonmail.com> --- src/SimpleLoggerFactory.php | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/SimpleLoggerFactory.php b/src/SimpleLoggerFactory.php index 3ec0b81..13eddc7 100644 --- a/src/SimpleLoggerFactory.php +++ b/src/SimpleLoggerFactory.php @@ -3,6 +3,7 @@ declare( strict_types=1 ); namespace WPDesk\Logger; +use Monolog\Handler\FingersCrossedHandler; use Monolog\Handler\HandlerInterface; use Monolog\Logger; use Monolog\Handler\ErrorLogHandler; @@ -16,6 +17,7 @@ final class SimpleLoggerFactory implements LoggerFactory { /** * @var array{ * level?: string, + * action_level?: string|null, * } */ private $options; @@ -29,6 +31,7 @@ final class SimpleLoggerFactory implements LoggerFactory { /** * Valid options are: * * level (default debug): Default logging level + * * action_level: If value is set, it will act as the minimum level at which logger will be triggered using FingersCrossedHandler {@see https://seldaek.github.io/monolog/doc/02-handlers-formatters-processors.html#wrappers--special-handlers} */ public function __construct( string $channel, $options = null ) { $this->channel = $channel; @@ -40,6 +43,7 @@ final class SimpleLoggerFactory implements LoggerFactory { $this->options = array_merge( [ 'level' => LogLevel::DEBUG, + 'action_level' => null, ], $options ); @@ -58,9 +62,9 @@ final class SimpleLoggerFactory implements LoggerFactory { ); if ( \function_exists( 'wc_get_logger' ) && \did_action( 'woocommerce_init' ) ) { - $this->create_wc_handler(); + $this->set_wc_handler(); } else { - \add_action( 'woocommerce_init', [ $this, 'create_wc_handler' ] ); + \add_action( 'woocommerce_init', [ $this, 'set_wc_handler' ] ); } // In the worst-case scenario, when WC logs are not available (yet, or at all), @@ -86,6 +90,10 @@ final class SimpleLoggerFactory implements LoggerFactory { } private function set_handler( Logger $logger, HandlerInterface $handler ): void { + if ( is_string( $this->options['action_level'] ) ) { + $handler = new FingersCrossedHandler( $handler, $this->options['action_level'] ); + } + // Purposefully replace all existing handlers. $logger->setHandlers( [ $handler ] ); } -- GitLab