Просмотр исходного кода

Merge pull request #267 from cordoval/feature/logrotate_flexible

plug #245 log rotate with setTimedFilename
Jordi Boggiano 12 лет назад
Родитель
Сommit
43f97bb5af
1 измененных файлов с 32 добавлено и 7 удалено
  1. 32 7
      src/Monolog/Handler/RotatingFileHandler.php

+ 32 - 7
src/Monolog/Handler/RotatingFileHandler.php

@@ -28,6 +28,8 @@ class RotatingFileHandler extends StreamHandler
     protected $maxFiles;
     protected $mustRotate;
     protected $nextRotation;
+    protected $filenameFormat;
+    protected $dateFormat;
 
     /**
      * @param string  $filename
@@ -40,6 +42,8 @@ class RotatingFileHandler extends StreamHandler
         $this->filename = $filename;
         $this->maxFiles = (int) $maxFiles;
         $this->nextRotation = new \DateTime('tomorrow');
+        $this->filenameFormat = '{filename}-{date}';
+        $this->dateFormat = 'Y-m-d';
 
         parent::__construct($this->getTimedFilename(), $level, $bubble);
     }
@@ -56,6 +60,12 @@ class RotatingFileHandler extends StreamHandler
         }
     }
 
+    public function setFilenameFormat($filenameFormat, $dateFormat)
+    {
+        $this->filenameFormat = $filenameFormat;
+        $this->dateFormat = $dateFormat;
+    }
+
     /**
      * {@inheritdoc}
      */
@@ -88,12 +98,7 @@ class RotatingFileHandler extends StreamHandler
             return;
         }
 
-        $fileInfo = pathinfo($this->filename);
-        $glob = $fileInfo['dirname'].'/'.$fileInfo['filename'].'-*';
-        if (!empty($fileInfo['extension'])) {
-            $glob .= '.'.$fileInfo['extension'];
-        }
-        $logFiles = glob($glob);
+        $logFiles = glob($this->getGlobPattern());
         if ($this->maxFiles >= count($logFiles)) {
             // no files to remove
             return;
@@ -114,11 +119,31 @@ class RotatingFileHandler extends StreamHandler
     protected function getTimedFilename()
     {
         $fileInfo = pathinfo($this->filename);
-        $timedFilename = $fileInfo['dirname'].'/'.$fileInfo['filename'].'-'.date('Y-m-d');
+        $timedFilename = str_replace(
+            array('{filename}', '{date}'),
+            array($fileInfo['filename'], date($this->dateFormat)),
+            $fileInfo['dirname'] . '/' . $this->filenameFormat
+        );
+
         if (!empty($fileInfo['extension'])) {
             $timedFilename .= '.'.$fileInfo['extension'];
         }
 
         return $timedFilename;
     }
+
+    protected function getGlobPattern()
+    {
+        $fileInfo = pathinfo($this->filename);
+        $glob = str_replace(
+            array('{filename}', '{date}'),
+            array($fileInfo['filename'], '*'),
+            $fileInfo['dirname'] . '/' . $this->filenameFormat
+        );
+        if (!empty($fileInfo['extension'])) {
+            $glob .= '.'.$fileInfo['extension'];
+        }
+
+        return $glob;
+    }
 }