Skip to content

Commit

Permalink
Merge pull request #5 from cesargb/prev2
Browse files Browse the repository at this point in the history
v2 api
  • Loading branch information
cesargb committed Mar 22, 2021
2 parents fede786 + 524b290 commit 3880d30
Show file tree
Hide file tree
Showing 14 changed files with 405 additions and 179 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ jobs:
strategy:
fail-fast: false
matrix:
php: [7.3, 7.4, 8.0]
php: [7.4, 8.0]

name: P${{ matrix.php }}

Expand Down
22 changes: 22 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Listen for XDebug",
"type": "php",
"request": "launch",
"port": 9000
},
{
"name": "Launch currently open script",
"type": "php",
"request": "launch",
"program": "${file}",
"cwd": "${fileDirname}",
"port": 9000
}
]
}
41 changes: 9 additions & 32 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ This class permit log rotating with diferetne processor.
[![tests](https://github.com/cesargb/php-log-rotation/workflows/tests/badge.svg)](https://github.com/cesargb/php-log-rotation/actions)
[![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)

Note: If you have the version 1 installed, [read this](https://github.com/cesargb/php-log-rotation/tree/v1).

## Installation

You can install this package via composer using:
Expand All @@ -17,45 +19,20 @@ composer require cesargb/php-log-rotation

## Usage

This is an example:

```php
use Cesargb\Log\Rotation;
use Cesargb\Log\Processors\GzProcessor;
use Cesargb\Log\Processors\RotativeProcessor;

$fileLog='file.log';
$fileMaxSize=50; // only rotate log if over 50MB

$rotation = new Rotation();

$rotation->addProcessor(new GzProcessor());
->addProcessor(new RotativeProcessor())
->rotate($fileLog, $fileMaxSize);
$rotation
->compress() // Optional, compress the file after rotated
->files(30) // Optional, files are rotated 30 times before being removed
->minSize(1024) // Optional, are rotated when they grow bigger than 1024 bytes
->then(function ($filename) {}) // Optional, to get filename rotated
->catch(function ($exception) {}) // Optional, to catch a exception in rotating
->rotate('file.log');
```

## Processor

After of move the content of current log file, you can process changes in
the file was rotated.

### GzProcessor

This processor permit compress in gz format the file rotated.

### RotativeProcessor

This processor permit rotative each file in format file.log.1, file.log.2, ...

You can call method `setMaxFiles` to set the number max of the files rotated.
By default is 366 (One year if rotate each day).

## Todo

[ ] Processor Prefix; To add prefix to file rotated, sample: date (yyyy-mm-dd)
[ ] Processor Archive; To move the file rotated to other dir.
[ ] Processors to move to the cloud

## Test
Run test with:

Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
],
"license": "MIT",
"require": {
"php": "^7.3 || ^8.0"
"php": "^7.4 || ^8.0"
},
"autoload": {
"psr-4": {
Expand Down
39 changes: 39 additions & 0 deletions src/Compress/Gz.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace Cesargb\Log\Compress;

use Exception;

class Gz
{
const EXTENSION_COMPRESS = 'gz';

public function handler($file): string
{
$fileCompress = $file.'.'.self::EXTENSION_COMPRESS;

$fd = fopen($file, 'r');

if (!$fd) {
throw new Exception("file {$file} not can read.", 100);
}

$gz = gzopen($fileCompress, 'wb');

if (! $gz) {
fclose($fd);

throw new Exception("file {$fileCompress} not can open.", 101);
}

while (! feof($fd)) {
gzwrite($gz, fread($fd, 1024 * 512));
}

gzclose($gz);
fclose($fd);
unlink($file);

return $fileCompress;
}
}
28 changes: 28 additions & 0 deletions src/ErrorHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace Cesargb\Log;

use Throwable;

class ErrorHandler
{
private $catchCallable = null;

public function catch(callable $callable): self
{
$this->catchCallable = $callable;

return $this;
}

public function exception(Throwable $exception): self
{
if ($this->catchCallable) {
call_user_func($this->catchCallable, $exception);
} else {
throw $exception;
}

return $this;
}
}
13 changes: 10 additions & 3 deletions src/Processors/AbstractProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@

abstract class AbstractProcessor
{
private $fileOut;
private string $fileOut;

protected $fileOriginal;
protected string $fileOriginal;

protected string $suffix = '';

abstract public function handler($file): ?string;

Expand All @@ -15,7 +17,12 @@ public function __construct()
clearstatcache();
}

public function setFileOriginal($fileOriginal)
public function compress(): void
{
$this->suffix = '.gz';
}

public function setFileOriginal($fileOriginal): self
{
$this->fileOriginal = $fileOriginal;

Expand Down
37 changes: 0 additions & 37 deletions src/Processors/GzProcessor.php

This file was deleted.

59 changes: 30 additions & 29 deletions src/Processors/RotativeProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,58 +7,59 @@ class RotativeProcessor extends AbstractProcessor
private $maxFiles = 366;

/**
* Max num file rotate
* Log files are rotated count times before being removed
*
* @param int $maxFiles
* @param int $count
* @return self
*/
public function setMaxFiles(int $maxFiles): self
public function files(int $count): self
{
$this->maxFiles = $maxFiles;
$this->maxFiles = $count;

return $this;
}

public function handler($file): ?string
{
$fileInfo = pathinfo($file);
$nextFile = "{$this->fileOriginal}.1";

$extension_in = $fileInfo['extension'] ?? '';
$this->rotate();

$fileInfo = pathinfo($this->fileOriginal);
rename($file, $nextFile);

$extension_original = $fileInfo['extension'] ?? '';
return $this->processed($nextFile);
}

$glob = $fileInfo['dirname'].DIRECTORY_SEPARATOR.$fileInfo['filename'];
private function rotate(int $number = 1): string
{
$file = "{$this->fileOriginal}.{$number}{$this->suffix}";

if (! empty($fileInfo['extension'])) {
$glob .= '.'.$fileInfo['extension'];
if (!file_exists($file)) {
return "{$this->fileOriginal}.{$number}{$this->suffix}";
}

if ($extension_in != '' && $extension_in != $extension_original) {
$glob .= '.'.$extension_in;
}
if ($this->maxFiles > 0 && $number >= $this->maxFiles ) {
if (file_exists($file)) {
unlink($file);
}

$glob .= '.*';
return "{$this->fileOriginal}.{$number}{$this->suffix}";
}

$curFiles = glob($glob);
$nextFile = $this->rotate($number + 1);

for ($n = count($curFiles); $n > 0; $n--) {
$file_to_move = str_replace('*', $n, $glob);
rename($file, $nextFile);

if (file_exists($file_to_move)) {
if ($this->maxFiles > 0 && $n >= $this->maxFiles) {
unlink($file_to_move);
} else {
rename($file_to_move, str_replace('*', $n + 1, $glob));
}
}
}
return "{$this->fileOriginal}.{$number}{$this->suffix}";
}

$nextFile = str_replace('*', '1', $glob);
private function getnumber(string $file): ?int
{
$fileName = basename($file);
$fileOriginaleName = basename($this->fileOriginal);

rename($file, $nextFile);
preg_match("/{$fileOriginaleName}.([0-9]+){$this->suffix}/", $fileName, $output);

return $this->processed($nextFile);
return $output[1] ?? null;
}
}
Loading

0 comments on commit 3880d30

Please sign in to comment.