From 78e6df032eb12f478cea2615b5339651a928dddd Mon Sep 17 00:00:00 2001 From: Chuoke Date: Fri, 24 Oct 2025 16:29:18 +0800 Subject: [PATCH] feat: Add automatic empty directory cleanup in RotatingFileHandler (#2000) * feat: RotatingHandler Capable of handling log files in nested directory format --- src/Monolog/Handler/RotatingFileHandler.php | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/Monolog/Handler/RotatingFileHandler.php b/src/Monolog/Handler/RotatingFileHandler.php index 3077338f..4063c841 100644 --- a/src/Monolog/Handler/RotatingFileHandler.php +++ b/src/Monolog/Handler/RotatingFileHandler.php @@ -146,6 +146,8 @@ class RotatingFileHandler extends StreamHandler return strcmp($b, $a); }); + $basePath = dirname($this->filename); + foreach (\array_slice($logFiles, $this->maxFiles) as $file) { if (is_writable($file)) { // suppress errors here as unlink() might fail if two processes @@ -154,6 +156,17 @@ class RotatingFileHandler extends StreamHandler return true; }); unlink($file); + + $dir = dirname($file); + while ($dir !== $basePath) { + $entries = scandir($dir); + if ($entries === false || \count(array_diff($entries, ['.', '..'])) > 0) { + break; + } + + rmdir($dir); + $dir = dirname($dir); + } restore_error_handler(); } }