Skip to content
Snippets Groups Projects
Select Git revision
  • a98f738cdd67f5a4aafe4bcb7f2f4d7206beab29
  • master default protected
  • feat/message-handling
  • feat/request-id
  • 1.13.2
  • 1.13.1
  • 1.13.0
  • 1.12.1
  • 1.12.0
  • 1.11.0
  • 1.11.0-beta2
  • 1.11.0-beta1
  • 1.10.2
  • 1.10.1
  • 1.10.0
  • 1.9.0
  • 1.8.0
  • 1.7.4
  • 1.7.3
  • 1.7.2
  • 1.7.1
  • 1.7.0
  • 1.6.2
  • 1.6.2-beta2
24 results

SimpleLoggerFactory.php

Blame
  • SimpleLoggerFactory.php 1.71 KiB
    <?php
    declare( strict_types=1 );
    
    namespace WPDesk\Logger;
    
    use Monolog\Handler\HandlerInterface;
    use Monolog\Handler\NullHandler;
    use Monolog\Logger;
    use Monolog\Handler\ErrorLogHandler;
    use WPDesk\Logger\WC\WooCommerceHandler;
    
    final class SimpleLoggerFactory implements LoggerFactory {
    
    	/** @var Settings */
    	private $options;
    
    	/** @var string */
    	private $channel;
    
    	/** @var Logger */
    	private $logger;
    
    	public function __construct( string $channel, Settings $options = null ) {
    		$this->channel = $channel;
    		$this->options = $options ?? new Settings();
    	}
    
    	public function getLogger( $name = null ): Logger {
    		if ( $this->logger ) {
    			return $this->logger;
    		}
    
    		$this->logger = new Logger( $this->channel );
    
    		if ( $this->options->use_wc_log ) {
    			if ( \function_exists( 'wc_get_logger' ) && \did_action( 'woocommerce_init' ) ) {
    				$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( $this->logger->getHandlers() ) ) {
    			$this->logger->pushHandler( $this->get_wp_handler() );
    		}
    
    		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 {
    		if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
    			return new ErrorLogHandler( ErrorLogHandler::OPERATING_SYSTEM, $this->options->level );
    		}