From 3fa5b2f36d263f59beb755ed2a693ce9df1f0eb2 Mon Sep 17 00:00:00 2001 From: William Johnston Date: Tue, 14 Jul 2015 13:19:53 -0500 Subject: [PATCH] Create directory on initial log write rather than class instantiation. --- src/Monolog/Handler/StreamHandler.php | 30 ++++++++++++++++++--------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/src/Monolog/Handler/StreamHandler.php b/src/Monolog/Handler/StreamHandler.php index 1714b0f4..7f203427 100644 --- a/src/Monolog/Handler/StreamHandler.php +++ b/src/Monolog/Handler/StreamHandler.php @@ -27,6 +27,7 @@ class StreamHandler extends AbstractProcessingHandler private $errorMessage; protected $filePermission; protected $useLocking; + private $dirCreated; /** * @param resource|string $stream @@ -44,16 +45,6 @@ class StreamHandler extends AbstractProcessingHandler if (is_resource($stream)) { $this->stream = $stream; } elseif (is_string($stream)) { - $dir = $this->getDirFromStream($stream); - if (null !== $dir && !is_dir($dir)) { - $this->errorMessage = null; - set_error_handler(array($this, 'customErrorHandler')); - $status = mkdir($dir, 0777, true); - restore_error_handler(); - if (false === $status) { - throw new \UnexpectedValueException(sprintf('There is no existing directory at "%s" and its not buildable: '.$this->errorMessage, $dir)); - } - } $this->url = $stream; } else { throw new \InvalidArgumentException('A stream must either be a resource or a string.'); @@ -83,6 +74,7 @@ class StreamHandler extends AbstractProcessingHandler if (!$this->url) { throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().'); } + $this->createDir(); $this->errorMessage = null; set_error_handler(array($this, 'customErrorHandler')); $this->stream = fopen($this->url, 'a'); @@ -131,4 +123,22 @@ class StreamHandler extends AbstractProcessingHandler return; } + + private function createDir() + { + // Do not try to create dir if it has already been tried. + if ($this->dirCreated) return; + + $dir = $this->getDirFromStream($this->url); + if (null !== $dir && !is_dir($dir)) { + $this->errorMessage = null; + set_error_handler(array($this, 'customErrorHandler')); + $status = mkdir($dir, 0777, true); + restore_error_handler(); + if (false === $status) { + throw new \UnexpectedValueException(sprintf('There is no existing directory at "%s" and its not buildable: '.$this->errorMessage, $dir)); + } + } + $this->dirCreated = true; + } }