├── LICENSE ├── README.md ├── composer.json └── src ├── Compress └── Gz.php ├── ErrorHandler.php ├── Exceptions └── RotationFailed.php ├── Optionable.php ├── Processors ├── AbstractProcessor.php └── RotativeProcessor.php └── Rotation.php /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Cesar Garcia 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # PHP class to logs rotation 3 | 4 | This PHP package allows you to rotate a log file and compress it. 5 | 6 | [![tests](https://github.com/cesargb/php-log-rotation/workflows/tests/badge.svg)](https://github.com/cesargb/php-log-rotation/actions) 7 | [![phpstan](https://github.com/cesargb/php-log-rotation/actions/workflows/phpstan.yml/badge.svg)](https://github.com/cesargb/php-log-rotation/actions/workflows/phpstan.yml) 8 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/cesargb/php-log-rotation.svg?style=flat-square&color=brightgreen)](https://packagist.org/packages/cesargb/php-log-rotation) 9 | [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/cesargb/php-log-rotation/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/cesargb/php-log-rotation/?branch=master) 10 | 11 | Note: If you have the version 1 installed, [read this](https://github.com/cesargb/php-log-rotation/tree/v1). 12 | 13 | ## Installation 14 | 15 | You can install this package via composer using: 16 | 17 | ```bash 18 | composer require cesargb/php-log-rotation 19 | ``` 20 | 21 | ## Usage 22 | 23 | ```php 24 | use Cesargb\Log\Rotation; 25 | use Cesargb\Log\Exceptions\RotationFailed; 26 | 27 | $rotation = new Rotation(); 28 | 29 | $rotation 30 | ->compress() // Optional, compress the file after rotated. Accept level compression argument. 31 | ->files(30) // Optional, files are rotated 30 times before being removed. Default 366 32 | ->minSize(1024) // Optional, are rotated when they grow bigger than 1024 bytes. Default 0 33 | ->truncate() // Optional, truncate the original log file in place after creating a copy, instead of moving the old log file. 34 | ->then(function ($filenameTarget, $filenameRotated) {}) // Optional, to get filename target and original filename 35 | ->catch(function (RotationFailed $exception) {}) // Optional, to catch a exception in rotating 36 | ->finally(function ($message, $filenameTarget) {}) // Optional, this method will be called when the process has finished 37 | ->rotate('file.log'); 38 | ``` 39 | 40 | Or you can define the options in the constructor 41 | 42 | ```php 43 | use Cesargb\Log\Rotation; 44 | use Cesargb\Log\Exceptions\RotationFailed; 45 | 46 | $rotation = new Rotation([ 47 | 'files' => 1, 48 | 'compress' => true, // Set level compression or true to default level. Default false 49 | 'min-size' => 10, 50 | 'truncate' => false, 51 | 'then' => function ($filename) {}, 52 | 'catch' => function (RotationFailed $exception) {}, 53 | 'finally' => function ($message, $filename) {}, 54 | ]); 55 | 56 | $rotation->rotate('file.log'); 57 | ``` 58 | 59 | ## Test 60 | 61 | Run test with: 62 | 63 | ```bash 64 | composer test 65 | ``` 66 | 67 | ## Contributing 68 | 69 | Any contributions are welcome. 70 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cesargb/php-log-rotation", 3 | "description": "PHP Class to rotate log files", 4 | "type": "library", 5 | "keywords": [ 6 | "php", 7 | "log", 8 | "rotation" 9 | ], 10 | "homepage": "https://github.com/cesargb/php-log-rotation", 11 | "authors": [ 12 | { 13 | "name": "Cesar Garcia", 14 | "email": "cesargb@gmail.com" 15 | } 16 | ], 17 | "license": "MIT", 18 | "require": { 19 | "php": "^8.0" 20 | }, 21 | "autoload": { 22 | "psr-4": { 23 | "Cesargb\\Log\\": "src" 24 | } 25 | }, 26 | "autoload-dev": { 27 | "psr-4": { 28 | "Cesargb\\Log\\Test\\": "tests" 29 | } 30 | }, 31 | "scripts": { 32 | "test": "vendor/bin/phpunit" 33 | }, 34 | "require-dev": { 35 | "phpunit/phpunit": "^9.0", 36 | "phpstan/phpstan": "^1.9" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Compress/Gz.php: -------------------------------------------------------------------------------- 1 | thenCallback = $callable; 27 | 28 | return $this; 29 | } 30 | 31 | /** 32 | * Call function if roteted catch any Exception. 33 | */ 34 | public function catch(Closure $callable): self 35 | { 36 | $this->catchCallable = $callable; 37 | 38 | return $this; 39 | } 40 | 41 | /** 42 | * Function that will be executed when the process was finished. 43 | */ 44 | public function finally(Closure $callable): self 45 | { 46 | $this->finallyCallback = $callable; 47 | 48 | return $this; 49 | } 50 | 51 | protected function setFilename(string $filename): void 52 | { 53 | $this->_filename = $filename; 54 | } 55 | 56 | private function successful(string $filenameSource, ?string $filenameRotated): void 57 | { 58 | $this->finished('successful', $filenameSource); 59 | 60 | if (is_null($this->thenCallback) || is_null($filenameRotated)) { 61 | return; 62 | } 63 | 64 | call_user_func($this->thenCallback, $filenameRotated, $filenameSource); 65 | } 66 | 67 | protected function exception(Throwable $exception): self 68 | { 69 | $this->finished($exception->getMessage(), $this->_filename); 70 | 71 | if ($this->catchCallable) { 72 | call_user_func($this->catchCallable, $this->convertException($exception)); 73 | } else { 74 | throw $this->convertException($exception); 75 | } 76 | 77 | return $this; 78 | } 79 | 80 | 81 | protected function finished(string $message, ?string $filenameSource): void 82 | { 83 | if (is_null($this->finallyCallback)) { 84 | return; 85 | } 86 | 87 | call_user_func($this->finallyCallback, $message, $filenameSource); 88 | } 89 | 90 | private function convertException(Throwable $exception): RotationFailed 91 | { 92 | return new RotationFailed( 93 | $exception->getMessage(), 94 | $exception->getCode(), 95 | $exception->getPrevious(), 96 | $this->_filename 97 | ); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/Exceptions/RotationFailed.php: -------------------------------------------------------------------------------- 1 | filename = $filename ?? ''; 17 | } 18 | 19 | public function getFilename(): ?string 20 | { 21 | return $this->filename; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Optionable.php: -------------------------------------------------------------------------------- 1 | $value) { 24 | $this->setMethod($key, $value); 25 | } 26 | 27 | return $this; 28 | } 29 | 30 | /** 31 | * @param string[] $methods 32 | */ 33 | protected function methodsOptionables(array $methods): self 34 | { 35 | $this->validMethods = $methods; 36 | 37 | return $this; 38 | } 39 | 40 | private function setMethod(string $key, mixed $value): void 41 | { 42 | $method = $this->convert($key); 43 | 44 | if (in_array($method, $this->validMethods)) { 45 | $this->{$method}($value); 46 | } else { 47 | throw new LogicException("option {$key} is not valid.", 30); 48 | } 49 | } 50 | 51 | private function convert(string $key): string 52 | { 53 | return lcfirst( 54 | str_replace( 55 | ' ', 56 | '', 57 | ucwords(str_replace(['-', '_'], ' ', $key)) 58 | ) 59 | ); 60 | } 61 | 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/Processors/AbstractProcessor.php: -------------------------------------------------------------------------------- 1 | extension = '.'.$extension; 21 | } 22 | 23 | public function removeExtension(string $extension): void 24 | { 25 | $this->extension = str_replace('.'.$extension, '', $this->extension); 26 | } 27 | 28 | public function setFilenameSource(string $filenameSource): self 29 | { 30 | $this->filenameSource = $filenameSource; 31 | 32 | return $this; 33 | } 34 | 35 | protected function processed(string $filename): ?string 36 | { 37 | return is_file($filename) ? $filename : null; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Processors/RotativeProcessor.php: -------------------------------------------------------------------------------- 1 | maxFiles = $count; 15 | 16 | return $this; 17 | } 18 | 19 | public function handler(string $filename): ?string 20 | { 21 | $filenameTarget = "{$this->filenameSource}.1"; 22 | 23 | $this->rotate(); 24 | 25 | rename($filename, $filenameTarget); 26 | 27 | return $this->processed($filenameTarget); 28 | } 29 | 30 | private function rotate(int $number = 1): string 31 | { 32 | $filenameTarget = "{$this->filenameSource}.{$number}{$this->extension}"; 33 | 34 | if (!file_exists($filenameTarget)) { 35 | return $filenameTarget; 36 | } 37 | 38 | if ($this->maxFiles > 0 && $number >= $this->maxFiles) { 39 | unlink($filenameTarget); 40 | 41 | return $filenameTarget; 42 | } 43 | 44 | $nextFilename = $this->rotate($number + 1); 45 | 46 | rename($filenameTarget, $nextFilename); 47 | 48 | return $filenameTarget; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/Rotation.php: -------------------------------------------------------------------------------- 1 | processor = new RotativeProcessor(); 31 | 32 | $this->methodsOptionables([ 33 | 'compress', 34 | 'truncate', 35 | 'minSize', 36 | 'files', 37 | 'then', 38 | 'catch', 39 | 'finally', 40 | ]); 41 | 42 | $this->options($options); 43 | } 44 | 45 | /** 46 | * Log files are rotated count times before being removed. 47 | */ 48 | public function files(int $count): self 49 | { 50 | $this->processor->files($count); 51 | 52 | return $this; 53 | } 54 | 55 | /** 56 | * Old versions of log files are compressed. 57 | */ 58 | public function compress(bool|int $level = true): self 59 | { 60 | $this->_compress = (bool)($level); 61 | $this->_compressLevel = is_numeric($level) 62 | ? $level 63 | : self::COMPRESS_DEFAULT_LEVEL; 64 | 65 | if ($this->_compress) { 66 | $this->processor->addExtension('gz'); 67 | } else { 68 | $this->processor->removeExtension('gz'); 69 | } 70 | 71 | return $this; 72 | } 73 | 74 | /** 75 | * Truncate the original log file in place after creating a copy, instead of 76 | * moving the old log file. 77 | * 78 | * It can be used when some program cannot be told to close its logfile and 79 | * thus might continue writing (appending) to the previous log file forever. 80 | */ 81 | public function truncate(bool $truncate = true): self 82 | { 83 | $this->_truncate = $truncate; 84 | 85 | return $this; 86 | } 87 | 88 | /** 89 | * Log files are rotated when they grow bigger than size bytes. 90 | */ 91 | public function minSize(int $bytes): self 92 | { 93 | $this->_minSize = $bytes; 94 | 95 | return $this; 96 | } 97 | 98 | /** 99 | * Rotate file. 100 | * 101 | * @return bool true if rotated was successful 102 | */ 103 | public function rotate(string $filename): bool 104 | { 105 | $this->setFilename($filename); 106 | 107 | if (!$this->canRotate($filename)) { 108 | return false; 109 | } 110 | 111 | $fileTemporary = $this->_truncate 112 | ? $this->copyAndTruncate($filename) 113 | : $this->move($filename); 114 | 115 | if (is_null($fileTemporary)) { 116 | return false; 117 | } 118 | 119 | $fileTarget = $this->runProcessor( 120 | $filename, 121 | $fileTemporary 122 | ); 123 | 124 | if (is_null($fileTarget)) { 125 | return false; 126 | } 127 | 128 | $fileTarget = $this->runCompress($fileTarget); 129 | 130 | $this->successful($filename, $fileTarget); 131 | 132 | return true; 133 | } 134 | 135 | /** 136 | * Run processor. 137 | */ 138 | private function runProcessor(string $filenameSource, ?string $filenameTarget): ?string 139 | { 140 | $this->initProcessorFile($filenameSource); 141 | 142 | if (!$filenameTarget) { 143 | return null; 144 | } 145 | 146 | return $this->processor->handler($filenameTarget); 147 | } 148 | 149 | private function runCompress(string $filename): ?string 150 | { 151 | if (!$this->_compress) { 152 | return $filename; 153 | } 154 | 155 | $gz = new Gz(); 156 | 157 | try { 158 | return $gz->handler($filename, $this->_compressLevel); 159 | } catch (Exception $error) { 160 | $this->exception($error); 161 | 162 | return null; 163 | } 164 | } 165 | 166 | /** 167 | * check if file need rotate. 168 | */ 169 | private function canRotate(string $filename): bool 170 | { 171 | if (!file_exists($filename)) { 172 | $this->finished(sprintf('the file %s not exists.', $filename), $filename); 173 | 174 | return false; 175 | } 176 | 177 | if (!$this->fileIsValid($filename)) { 178 | $this->exception( 179 | new Exception(sprintf('the file %s not is valid.', $filename), 10) 180 | ); 181 | 182 | return false; 183 | } 184 | 185 | return filesize($filename) > ($this->_minSize > 0 ? $this->_minSize : 0); 186 | } 187 | 188 | /** 189 | * Set original File to processor. 190 | */ 191 | private function initProcessorFile(string $filename): void 192 | { 193 | $this->processor->setFilenameSource($filename); 194 | } 195 | 196 | /** 197 | * check if file is valid to rotate. 198 | */ 199 | private function fileIsValid(string $filename): bool 200 | { 201 | return is_file($filename) && is_writable($filename); 202 | } 203 | 204 | /** 205 | * copy data to temp file and truncate. 206 | */ 207 | private function copyAndTruncate(string $filename): ?string 208 | { 209 | clearstatcache(); 210 | 211 | $filenameTarget = $this->getTempFilename(dirname($filename)); 212 | 213 | if (!$filenameTarget) { 214 | return null; 215 | } 216 | 217 | $fd = $this->openFileWithLock($filename); 218 | 219 | if (!$fd) { 220 | return null; 221 | } 222 | 223 | if (!copy($filename, $filenameTarget)) { 224 | fclose($fd); 225 | 226 | $this->exception( 227 | new Exception( 228 | sprintf('the file %s not can copy to temp file %s.', $filename, $filenameTarget), 229 | 22 230 | ) 231 | ); 232 | 233 | return null; 234 | } 235 | 236 | if (!ftruncate($fd, 0)) { 237 | fclose($fd); 238 | 239 | unlink($filenameTarget); 240 | 241 | $this->exception( 242 | new Exception(sprintf('the file %s not can truncate.', $filename), 23) 243 | ); 244 | 245 | return null; 246 | } 247 | 248 | flock($fd, LOCK_UN); 249 | 250 | fflush($fd); 251 | 252 | fclose($fd); 253 | 254 | return $filenameTarget; 255 | } 256 | 257 | private function move(string $filename): ?string 258 | { 259 | clearstatcache(); 260 | 261 | $filenameTarget = $this->getTempFilename(dirname($filename)); 262 | 263 | if (!$filenameTarget) { 264 | return null; 265 | } 266 | 267 | if (!rename($filename, $filenameTarget)) { 268 | $this->exception( 269 | new Exception( 270 | sprintf('the file %s not can move to temp file %s.', $filename, $filenameTarget), 271 | 22 272 | ) 273 | ); 274 | 275 | return null; 276 | } 277 | 278 | return $filenameTarget; 279 | } 280 | 281 | private function getTempFilename(string $path): ?string 282 | { 283 | $filename = tempnam($path, 'LOG'); 284 | 285 | if ($filename === false) { 286 | $this->exception( 287 | new Exception(sprintf('the file %s not can create temp file.', $path), 19) 288 | ); 289 | 290 | return null; 291 | } 292 | 293 | return $filename; 294 | } 295 | 296 | /** 297 | * @return null|resource 298 | */ 299 | private function openFileWithLock(string $filename) 300 | { 301 | $fd = fopen($filename, 'r+'); 302 | 303 | if ($fd === false) { 304 | $this->exception( 305 | new Exception(sprintf('the file %s not can open.', $filename), 20) 306 | ); 307 | 308 | return null; 309 | } 310 | 311 | if (!flock($fd, LOCK_EX)) { 312 | fclose($fd); 313 | 314 | $this->exception( 315 | new Exception(sprintf('the file %s not can lock.', $filename), 21) 316 | ); 317 | 318 | return null; 319 | } 320 | 321 | return $fd; 322 | } 323 | } 324 | --------------------------------------------------------------------------------