-
Notifications
You must be signed in to change notification settings - Fork 13
/
LoggingMiddleware.php
83 lines (66 loc) · 2.28 KB
/
LoggingMiddleware.php
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
declare(strict_types=1);
namespace Shoot\Shoot\Middleware;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
use Shoot\Shoot\HasPresenterInterface;
use Shoot\Shoot\MiddlewareInterface;
use Shoot\Shoot\View;
use Throwable;
/**
* Logs all views being processed by Shoot. It's recommended to add this before any other middleware.
*/
final class LoggingMiddleware implements MiddlewareInterface
{
/** @var LoggerInterface */
private $logger;
/**
* Constructs a new instance of LoggingMiddleware. Requires a PSR-3 compliant logger.
*
* @param LoggerInterface $logger
*/
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* Process the view within the context of the current HTTP request, either before or after calling the next
* middleware. Returns the processed view.
*
* @param View $view
* @param ServerRequestInterface $request
* @param callable $next
*
* @return View
*
* @throws Throwable
*/
public function process(View $view, ServerRequestInterface $request, callable $next): View
{
$context = [];
$message = $view->getName();
try {
$startTime = microtime(true);
/** @var View $view */
$view = $next($view);
$endTime = microtime(true);
$presentationModel = $view->getPresentationModel();
$context['presentation_model'] = $presentationModel->getName();
if ($presentationModel instanceof HasPresenterInterface) {
$context['presenter_name'] = $presentationModel->getPresenterName();
}
$context['time_taken'] = sprintf("%f seconds", $endTime - $startTime);
if ($view->hasSuppressedException()) {
$context['exception'] = $view->getSuppressedException();
$this->logger->warning($message, $context);
} else {
$this->logger->debug($message, $context);
}
return $view;
} catch (Throwable $exception) {
$context['exception'] = $exception;
$this->logger->error($message, $context);
throw $exception;
}
}
}