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

Make sure handlers can be closed multiple times

Jordi Boggiano 10 лет назад
Родитель
Сommit
3dccef613e

+ 13 - 1
src/Monolog/Handler/RollbarHandler.php

@@ -29,6 +29,13 @@ class RollbarHandler extends AbstractProcessingHandler
      */
     protected $rollbarNotifier;
 
+    /**
+     * Records whether any log records have been added since the last flush of the rollbar notifier
+     *
+     * @var bool
+     */
+    private $hasRecords = false;
+
     /**
      * @param RollbarNotifier $rollbarNotifier RollbarNotifier object constructed with valid token
      * @param integer         $level           The minimum logging level at which this handler will be triggered
@@ -61,6 +68,8 @@ class RollbarHandler extends AbstractProcessingHandler
                 array_merge($record['context'], $record['extra'], $extraData)
             );
         }
+
+        $this->hasRecords = true;
     }
 
     /**
@@ -68,6 +77,9 @@ class RollbarHandler extends AbstractProcessingHandler
      */
     public function close()
     {
-        $this->rollbarNotifier->flush();
+        if ($this->hasRecords) {
+            $this->rollbarNotifier->flush();
+            $this->hasRecords = false;
+        }
     }
 }

+ 2 - 0
src/Monolog/Handler/RotatingFileHandler.php

@@ -118,6 +118,8 @@ class RotatingFileHandler extends StreamHandler
                 unlink($file);
             }
         }
+
+        $this->mustRotate = false;
     }
 
     protected function getTimedFilename()

+ 7 - 1
src/Monolog/Handler/SyslogUdp/UdpSocket.php

@@ -29,11 +29,17 @@ class UdpSocket
 
     public function close()
     {
-        socket_close($this->socket);
+        if (is_resource($this->socket)) {
+            socket_close($this->socket);
+            $this->socket = null;
+        }
     }
 
     protected function send($chunk)
     {
+        if (!is_resource($this->socket)) {
+            throw new \LogicException('The UdpSocket to '.$this->ip.':'.$this->port.' has been closed and can not be written to anymore');
+        }
         socket_sendto($this->socket, $chunk, strlen($chunk), $flags = 0, $this->ip, $this->port);
     }
 

+ 18 - 0
tests/Monolog/Handler/UdpSocketTest.php

@@ -12,6 +12,7 @@
 namespace Monolog\Handler;
 
 use Monolog\TestCase;
+use Monolog\Handler\SyslogUdp\UdpSocket;
 
 /**
  * @requires extension sockets
@@ -43,4 +44,21 @@ class UdpSocketTest extends TestCase
 
         $socket->write($longString, "HEADER");
     }
+
+    public function testDoubleCloseDoesNotError()
+    {
+        $socket = new UdpSocket('127.0.0.1', 514);
+        $socket->close();
+        $socket->close();
+    }
+
+    /**
+     * @expectedException LogicException
+     */
+    public function testWriteAfterCloseErrors()
+    {
+        $socket = new UdpSocket('127.0.0.1', 514);
+        $socket->close();
+        $socket->write('foo', "HEADER");
+    }
 }