Explorar o código

Merge pull request #607 from APMG/master

Create directory on initial log write rather than class instantiation.
Jordi Boggiano %!s(int64=10) %!d(string=hai) anos
pai
achega
3f641e31cc
Modificáronse 1 ficheiros con 20 adicións e 10 borrados
  1. 20 10
      src/Monolog/Handler/StreamHandler.php

+ 20 - 10
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;
+    }
 }