Issues (11)

src/Utils/CacheLogger.php (1 issue)

1
<?php
2
3
namespace Silviooosilva\CacheerPhp\Utils;
4
5
6
/**
7
 * Class CacheLogger
8
 * @author Sílvio Silva <https://github.com/silviooosilva>
9
 * @package Silviooosilva\CacheerPhp
10
 */
11
class CacheLogger
12
{
13
    private $logFile;
14
    private $maxFileSize; // Tamanho máximo do arquivo em bytes (5MB)
15
    private $logLevel;
16
    private $logLevels = ['DEBUG', 'INFO', 'WARNING', 'ERROR'];
17
18
    public function __construct($logFile = 'cacheer.log', $maxFileSize = 5 * 1024 * 1024, $logLevel = 'DEBUG')
19
    {
20
        $this->logFile = $logFile;
21
        $this->maxFileSize = $maxFileSize;
22
        $this->logLevel = strtoupper($logLevel);
23
    }
24
25
    /**
26
    * @return void
27
    */
28
    public function info($message)
29
    {
30
        $this->log('INFO', $message);
31
    }
32
33
    /**
34
    * @return void
35
    */
36
    public function warning($message)
37
    {
38
        $this->log('WARNING', $message);
39
    }
40
41
    /**
42
    * @return void
43
    */
44
    public function error($message)
45
    {
46
        $this->log('ERROR', $message);
47
    }
48
49
    /**
50
    * @return void
51
    */
52
    public function debug($message)
53
    {
54
        $this->log('DEBUG', $message);
55
    }
56
57
    /**
58
    * @param mixed $level
59
    * @return string|int|false
60
    */
61
    private function shouldLog(mixed $level)
62
    {
63
        return array_search($level, $this->logLevels) >= array_search($this->logLevel, $this->logLevels);
0 ignored issues
show
Bug Best Practice introduced by
The expression return array_search($lev...evel, $this->logLevels) returns the type boolean which is incompatible with the documented return type false|integer|string.
Loading history...
64
    }
65
66
    /**
67
    * @return void
68
    */
69
    private function rotateLog()
70
    {
71
        if (file_exists($this->logFile) && filesize($this->logFile) >= $this->maxFileSize) {
72
            $date = date('Y-m-d_H-i-s');
73
            rename($this->logFile, "cacheer_$date.log");
74
        }
75
    }
76
77
    /**
78
    * @param mixed $level
79
    * @param string $message
80
    * @return void
81
    */
82
    private function log($level, $message)
83
    {
84
        if (!$this->shouldLog($level)) {
85
            return;
86
        }
87
88
        $this->rotateLog();
89
90
        $date = date('Y-m-d H:i:s');
91
        $logMessage = "[$date] [$level] $message" . PHP_EOL;
92
        file_put_contents($this->logFile, $logMessage, FILE_APPEND);
93
    }
94
}
95