Skip to content
Permalink
Browse files

Lazy LoggerHolder

  • Loading branch information...
mabar authored and f3l1x committed May 6, 2019
1 parent 9eae477 commit 57988c7322a307c64fbf5679aee1dfa936f219e2
Showing with 20 additions and 13 deletions.
  1. +1 −1 src/DI/MonologExtension.php
  2. +19 −12 src/LoggerHolder.php
@@ -153,7 +153,7 @@ public function afterCompile(ClassType $class): void
}
if ($config['holder']['enabled']) {
$initialize->addBody('Contributte\Monolog\LoggerHolder::setLogger($this->getByType(?));', [Logger::class]);
$initialize->addBody('Contributte\Monolog\LoggerHolder::setLogger($this->getByType(?));', [$this->prefix('logger.default'), Container::class]);
}
}
@@ -4,44 +4,51 @@
use Contributte\Monolog\Exception\Logic\InvalidStateException;
use Monolog\Logger;
use Nette\DI\Container;
use Psr\Log\LoggerInterface;
class LoggerHolder
{
/** @var Logger|null */
private static $logger;
/** @var string|null */
private static $loggerServiceName;
/** @var LoggerHolder|null */
/** @var Container|null */
private static $container;
/** @var static|null */
private static $instSelf;
/** @var Logger */
private $instLogger;
public function __construct(Logger $logger)
public static function setLogger(string $loggerServiceName, Container $container): void
{
$this->instLogger = $logger;
static::$loggerServiceName = $loggerServiceName;
static::$container = $container;
}
/**
* @return static
*/
public static function getInstance(): self
{
if (static::$logger === null) {
throw new InvalidStateException(sprintf('Call %s::setLogger to use %s::getInstance', static::class, static::class));
}
if (static::$instSelf === null) {
static::$instSelf = new static(static::$logger);
if (static::$loggerServiceName === null || static::$container === null) {
throw new InvalidStateException(sprintf('Call %s::setLogger to use %s::getInstance', static::class, static::class));
}
/** @var Logger $logger */
$logger = static::$container->getService(static::$loggerServiceName);
static::$instSelf = new static($logger);
}
return static::$instSelf;
}
public static function setLogger(Logger $logger): void
public function __construct(Logger $logger)
{
static::$logger = $logger;
$this->instLogger = $logger;
}
public function getLogger(): LoggerInterface

0 comments on commit 57988c7

Please sign in to comment.
You can’t perform that action at this time.