Repository navigation
Expand file tree
/
Copy pathErrorLogger.php
More file actions
50 lines (40 loc) · 1.67 KB
/
Copy pathErrorLogger.php
File metadata and controls
50 lines (40 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
declare(strict_types=1);
namespace TinyBlocks\Http\ErrorHandler\Internal;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
use Throwable;
use TinyBlocks\Http\CorrelationId\CorrelatedLogger;
use TinyBlocks\Http\CorrelationId\CorrelationId;
use TinyBlocks\Http\CorrelationId\CorrelationIdMiddleware;
use TinyBlocks\Http\ErrorHandler\ErrorHandlingSettings;
final readonly class ErrorLogger
{
private function __construct(private ?LoggerInterface $logger, private ErrorHandlingSettings $settings)
{
}
public static function from(?LoggerInterface $logger, ErrorHandlingSettings $settings): ErrorLogger
{
return new ErrorLogger(logger: $logger, settings: $settings);
}
public function log(int $status, ServerRequestInterface $request, Throwable $exception): void
{
if (is_null($this->logger) || !$this->settings->logErrors) {
return;
}
$correlationId = $request->getAttribute(CorrelationIdMiddleware::ATTRIBUTE_NAME);
$logger = $correlationId instanceof CorrelationId
? CorrelatedLogger::from(logger: $this->logger, correlationId: $correlationId)
: $this->logger;
$context = ['message' => $exception->getMessage()];
if ($this->settings->logErrorDetails) {
$context['exception'] = $exception::class;
$context['file'] = $exception->getFile();
$context['line'] = $exception->getLine();
$context['trace'] = $exception->getTraceAsString();
}
ClientErrorStatus::matches(status: $status)
? $logger->warning('error', $context)
: $logger->error('error', $context);
}
}