From 91e6800a6cccfe2c3cd542facc38cf8be473a06c Mon Sep 17 00:00:00 2001
From: Grzegorz Rola <grzegorz.rola@octolize.com>
Date: Thu, 3 Nov 2022 12:18:54 +0000
Subject: [PATCH] bugfix(factory): wc logger

---
 CHANGELOG.md                |  4 ++++
 src/Settings.php            | 11 +++++++++++
 src/SimpleLoggerFactory.php | 38 +++++++++++++++++++++++++------------
 3 files changed, 41 insertions(+), 12 deletions(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 69cf19a..fa7a08c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,7 @@
+## [1.10.1] - 2022-10-01
+### Fixed
+- WC logger initialisation
+
 ## [1.10.0] - 2022-08-16
 ### Added
 - en_CA, en_GB translators
diff --git a/src/Settings.php b/src/Settings.php
index 07fa978..aa648ce 100644
--- a/src/Settings.php
+++ b/src/Settings.php
@@ -15,4 +15,15 @@ final class Settings {
 	/** @var bool */
 	public $use_wp_log = true;
 
+	/**
+	 * @param string $level
+	 * @param bool   $use_wc_log
+	 * @param bool   $use_wp_log
+	 */
+	public function __construct( string $level = LogLevel::DEBUG, bool $use_wc_log = true, bool $use_wp_log = true ) {
+		$this->level      = $level;
+		$this->use_wc_log = $use_wc_log;
+		$this->use_wp_log = $use_wp_log;
+	}
+
 }
diff --git a/src/SimpleLoggerFactory.php b/src/SimpleLoggerFactory.php
index cfd2c0d..cf88a94 100644
--- a/src/SimpleLoggerFactory.php
+++ b/src/SimpleLoggerFactory.php
@@ -30,23 +30,37 @@ final class SimpleLoggerFactory implements LoggerFactory {
 			return $this->logger;
 		}
 
-		$logger = new Logger( $this->channel );
-
-		if ( $this->options->use_wc_log && \function_exists( 'wc_get_logger' ) ) {
-			$logger->pushHandler(
-				new WooCommerceHandler(
-					\wc_get_logger(),
-					$this->channel
-				)
-			);
+		$this->logger = new Logger( $this->channel );
+
+		if ( $this->options->use_wc_log ) {
+			if ( \function_exists( 'wc_get_logger' ) ) {
+				$this->create_wc_handler();
+			} else {
+				\add_action( 'woocommerce_init', [ $this, 'create_wc_handler' ] );
+			}
 		}
 
 		// Adding WooCommerce logger may have failed, if so add WP by default.
-		if ( $this->options->use_wp_log || empty( $logger->getHandlers() ) ) {
-			$logger->pushHandler( $this->get_wp_handler() );
+		if ( $this->options->use_wp_log || empty( $this->logger->getHandlers() ) ) {
+			$this->logger->pushHandler( $this->get_wp_handler() );
 		}
 
-		return $this->logger = $logger;
+		return $this->logger;
+	}
+
+	/**
+	 * @internal
+	 */
+	public function create_wc_handler() {
+		while ( ! $this->options->use_wp_log && ! empty( $this->logger->getHandlers() ) ) {
+			$this->logger->popHandler();
+		}
+		$this->logger->pushHandler(
+			new WooCommerceHandler(
+				\wc_get_logger(),
+				$this->channel
+			)
+		);
 	}
 
 	private function get_wp_handler(): HandlerInterface {
-- 
GitLab