Passed
Push — main ( ecc256...533307 )
by Nobufumi
02:21
created

LogPsr3::errorHandler()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 4
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * LogPsr3 class
5
 *
6
 * Provides logging functional.
7
 *
8
 * This class adheres to PSR-1 and PSR-12 coding standards and implements
9
 * PSR-3 (Logger Interface) for compatibility with PSR-3 consumers.
10
 *
11
 * @category Utility
12
 * @package  jidaikobo/log
13
 * @author   jidaikobo-shibata <[email protected]>
14
 * @license  MIT License <https://opensource.org/licenses/MIT>
15
 * @link     https://github.com/jidaikobo-shibata/log
16
 */
17
18
namespace Jidaikobo;
19
20
use Psr\Log\LoggerInterface;
21
use Psr\Log\LogLevel;
22
use InvalidArgumentException;
23
24
class LogPsr3 implements LoggerInterface
25
{
26
    private string $logFile;
27
    private int $maxFileSize;
28
29
    /**
30
     * Determine the location of the log file and the size at which the log should be rotated.
31
     *
32
     * @param string $logFile     path of log file
33
     * @param int    $maxFileSize log rotation size
34
     *
35
     * @return void
36
     */
37
    public function __construct(string $logFile, int $maxFileSize)
38
    {
39
        $this->logFile = $logFile;
40
        $this->maxFileSize = $maxFileSize;
41
    }
42
43
    /**
44
     * Register error and exception handlers.
45
     *
46
     * @return void
47
     */
48
    public function registerHandlers(): void
49
    {
50
        set_error_handler([$this, 'errorHandler']);
51
        set_exception_handler([$this, 'exceptionHandler']);
52
    }
53
54
    /**
55
     * Handle PHP errors and log them.
56
     *
57
     * @param int    $errno   The level of the error raised.
58
     * @param string $errstr  The error message.
59
     * @param string $errfile The filename that the error was raised in.
60
     * @param int    $errline The line number the error was raised at.
61
     *
62
     * @return bool Always returns false to allow PHP's default error handler.
63
     */
64
    public function errorHandler(int $errno, string $errstr, string $errfile, int $errline): bool
65
    {
66
        $errorMessage = "PHP Error [Level $errno]: $errstr in $errfile on line $errline";
67
        $this->write($errorMessage, 'ERROR');
68
        return false;
69
    }
70
71
    /**
72
     * Handle uncaught exceptions and log them.
73
     *
74
     * @param \Throwable $exception The uncaught exception.
75
     *
76
     * @return void
77
     */
78
    public function exceptionHandler(\Throwable $exception): void
79
    {
80
        $errorMessage = sprintf(
81
            "Uncaught Exception: %s in %s on line %d",
82
            $exception->getMessage(),
83
            $exception->getFile(),
84
            $exception->getLine()
85
        );
86
        $this->write($errorMessage, 'ERROR');
87
    }
88
89
    /**
90
     * Rotate the log file if it exceeds the maximum size.
91
     *
92
     * @return void
93
     */
94
    private function rotateLogFile(): void
95
    {
96
        if (file_exists($this->logFile) && filesize($this->logFile) > $this->maxFileSize) {
97
            rename($this->logFile, $this->logFile . '.' . time());
98
        }
99
    }
100
101
    /**
102
     * Write a message to the log file.
103
     *
104
     * @param mixed  $message The message to log.
105
     * @param string $level   The log level.
106
     *
107
     * @return void
108
     */
109
    public function write(mixed $message, string $level = 'INFO'): void
110
    {
111
        $this->rotateLogFile();
112
113
        // Ensure the log directory exists
114
        $logDir = dirname($this->logFile);
115
        if (!is_dir($logDir)) {
116
            mkdir($logDir, 0777, true);
117
        }
118
119
        // Format the message
120
        $formattedMessage = match (true) {
121
            $message === null => 'null',
122
            is_bool($message) => $message ? 'true' : 'false',
123
            is_int($message) => (string) $message,
124
            is_array($message) => var_export($message, true),
125
            is_object($message) => method_exists($message, '__toString')
126
                ? (string) $message
127
                : json_encode($message, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
128
            default => (string) $message
129
        };
130
131
        // Objectの場合はクラス名を記録
132
        $type = is_object($message) ? get_class($message) : gettype($message);
133
134
        $timestamp = date('Y-m-d H:i:s');
135
        $logEntry = "[$timestamp] [$level] [$type] $formattedMessage" . PHP_EOL;
136
137
        file_put_contents($this->logFile, $logEntry, FILE_APPEND | LOCK_EX);
138
    }
139
140
    /**
141
     * Logs with an arbitrary level.
142
     *
143
     * @param mixed                $level   The log level.
144
     * @param string|\Stringable   $message The log message.
145
     * @param array<string, mixed> $context Context array.
146
     *
147
     * @return void
148
     */
149
    public function log($level, $message, array $context = []): void
150
    {
151
        if (!in_array($level, $this->getLogLevels(), true)) {
152
            throw new InvalidArgumentException("Invalid log level: $level");
153
        }
154
155
        $message = $this->interpolate($message, $context);
156
        $this->write($message, strtoupper($level));
157
    }
158
159
    /**
160
     * Logs a emergency message.
161
     *
162
     * @param string $message               The message to log.
163
     * @param array<string, mixed> $context Additional context for the log message.
164
     *
165
     * @return void
166
     */
167
    public function emergency($message, array $context = []): void
168
    {
169
        $this->log(LogLevel::EMERGENCY, $message, $context);
170
    }
171
172
    /**
173
     * Logs a alert message.
174
     *
175
     * @param string $message               The message to log.
176
     * @param array<string, mixed> $context Additional context for the log message.
177
     *
178
     * @return void
179
     */
180
    public function alert($message, array $context = []): void
181
    {
182
        $this->log(LogLevel::ALERT, $message, $context);
183
    }
184
185
    /**
186
     * Logs a critical message.
187
     *
188
     * @param string $message               The message to log.
189
     * @param array<string, mixed> $context Additional context for the log message.
190
     *
191
     * @return void
192
     */
193
    public function critical($message, array $context = []): void
194
    {
195
        $this->log(LogLevel::CRITICAL, $message, $context);
196
    }
197
198
    /**
199
     * Logs a error message.
200
     *
201
     * @param string $message               The message to log.
202
     * @param array<string, mixed> $context Additional context for the log message.
203
     *
204
     * @return void
205
     */
206
    public function error($message, array $context = []): void
207
    {
208
        $this->log(LogLevel::ERROR, $message, $context);
209
    }
210
211
    /**
212
     * Logs a warning message.
213
     *
214
     * @param string $message               The message to log.
215
     * @param array<string, mixed> $context Additional context for the log message.
216
     *
217
     * @return void
218
     */
219
    public function warning($message, array $context = []): void
220
    {
221
        $this->log(LogLevel::WARNING, $message, $context);
222
    }
223
224
    /**
225
     * Logs a notice message.
226
     *
227
     * @param string $message               The message to log.
228
     * @param array<string, mixed> $context Additional context for the log message.
229
     *
230
     * @return void
231
     */
232
    public function notice($message, array $context = []): void
233
    {
234
        $this->log(LogLevel::NOTICE, $message, $context);
235
    }
236
237
    /**
238
     * Logs a info message.
239
     *
240
     * @param string $message               The message to log.
241
     * @param array<string, mixed> $context Additional context for the log message.
242
     *
243
     * @return void
244
     */
245
    public function info($message, array $context = []): void
246
    {
247
        $this->log(LogLevel::INFO, $message, $context);
248
    }
249
250
    /**
251
     * Logs a debug message.
252
     *
253
     * @param string $message               The message to log.
254
     * @param array<string, mixed> $context Additional context for the log message.
255
     *
256
     * @return void
257
     */
258
    public function debug($message, array $context = []): void
259
    {
260
        $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
261
        $traceInfo = array_map(
262
            function ($trace) {
263
                $file = $trace['file'] ?? '[internal function]';
264
                $line = $trace['line'] ?? '?';
265
                $function = $trace['function'];
266
                $class = $trace['class'] ?? '';
267
                return "$file:$line - {$class}{$function}()";
268
            },
269
            $backtrace
270
        );
271
272
        $message .= "\nTrace:\n" . implode("\n", $traceInfo);
273
274
        $this->write($message, 'DEBUG');
275
    }
276
277
    /**
278
     * Interpolates context values into the message placeholders.
279
     *
280
     * @param string $message               The message with placeholders.
281
     * @param array<string, mixed> $context The context array.
282
     *
283
     * @return string The interpolated message.
284
     */
285
    private function interpolate(string $message, array $context): string
286
    {
287
        $replacements = [];
288
        foreach ($context as $key => $value) {
289
            $replacements['{' . $key . '}'] = $value;
290
        }
291
292
        return strtr($message, $replacements);
293
    }
294
295
    /**
296
     * Get supported log levels.
297
     *
298
     * @return string[]
299
     */
300
    private function getLogLevels(): array
301
    {
302
        return [
303
            LogLevel::EMERGENCY,
304
            LogLevel::ALERT,
305
            LogLevel::CRITICAL,
306
            LogLevel::ERROR,
307
            LogLevel::WARNING,
308
            LogLevel::NOTICE,
309
            LogLevel::INFO,
310
            LogLevel::DEBUG,
311
        ];
312
    }
313
}
314