瀏覽代碼

Force log rotation on a daily basis even for long running processes, fixes #166

Jordi Boggiano 13 年之前
父節點
當前提交
953f21a7d8
共有 1 個文件被更改,包括 29 次插入12 次删除
  1. 29 12
      src/Monolog/Handler/RotatingFileHandler.php

+ 29 - 12
src/Monolog/Handler/RotatingFileHandler.php

@@ -20,12 +20,14 @@ use Monolog\Logger;
  * handle the rotation is strongly encouraged when you can use it.
  *
  * @author Christophe Coevoet <stof@notk.org>
+ * @author Jordi Boggiano <j.boggiano@seld.be>
  */
 class RotatingFileHandler extends StreamHandler
 {
     protected $filename;
     protected $maxFiles;
     protected $mustRotate;
+    protected $nextRotation;
 
     /**
      * @param string  $filename
@@ -37,19 +39,9 @@ class RotatingFileHandler extends StreamHandler
     {
         $this->filename = $filename;
         $this->maxFiles = (int) $maxFiles;
+        $this->nextRotation = new \DateTime('tomorrow');
 
-        $fileInfo = pathinfo($this->filename);
-        $timedFilename = $fileInfo['dirname'].'/'.$fileInfo['filename'].'-'.date('Y-m-d');
-        if (!empty($fileInfo['extension'])) {
-            $timedFilename .= '.'.$fileInfo['extension'];
-        }
-
-        // disable rotation upfront if files are unlimited
-        if (0 === $this->maxFiles) {
-            $this->mustRotate = false;
-        }
-
-        parent::__construct($timedFilename, $level, $bubble);
+        parent::__construct($this->getTimedFilename(), $level, $bubble);
     }
 
     /**
@@ -74,6 +66,11 @@ class RotatingFileHandler extends StreamHandler
             $this->mustRotate = !file_exists($this->url);
         }
 
+        if ($this->nextRotation < $record['datetime']) {
+            $this->mustRotate = true;
+            $this->close();
+        }
+
         parent::write($record);
     }
 
@@ -82,6 +79,15 @@ class RotatingFileHandler extends StreamHandler
      */
     protected function rotate()
     {
+        // update filename
+        $this->url = $this->getTimedFilename();
+        $this->nextRotation = new \DateTime('tomorrow');
+
+        // skip GC of old logs if files are unlimited
+        if (0 === $this->maxFiles) {
+            return;
+        }
+
         $fileInfo = pathinfo($this->filename);
         $glob = $fileInfo['dirname'].'/'.$fileInfo['filename'].'-*';
         if (!empty($fileInfo['extension'])) {
@@ -106,4 +112,15 @@ class RotatingFileHandler extends StreamHandler
             }
         }
     }
+
+    protected function getTimedFilename()
+    {
+        $fileInfo = pathinfo($this->filename);
+        $timedFilename = $fileInfo['dirname'].'/'.$fileInfo['filename'].'-'.date('Y-m-d');
+        if (!empty($fileInfo['extension'])) {
+            $timedFilename .= '.'.$fileInfo['extension'];
+        }
+
+        return $timedFilename;
+    }
 }