|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace TillKruss\LaravelTactician\Middleware; |
|
4
|
|
|
|
|
5
|
|
|
use Exception; |
|
6
|
|
|
use Throwable; |
|
7
|
|
|
use League\Tactician\Middleware; |
|
8
|
|
|
use Illuminate\Contracts\Logging\Log; |
|
9
|
|
|
use Illuminate\Foundation\Application; |
|
10
|
|
|
|
|
11
|
|
|
class LoggerMiddleware implements Middleware |
|
12
|
|
|
{ |
|
13
|
|
|
/** |
|
14
|
|
|
* The application instance. |
|
15
|
|
|
* |
|
16
|
|
|
* @var \Illuminate\Foundation\Application |
|
17
|
|
|
*/ |
|
18
|
|
|
protected $app; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* The logger instance. |
|
22
|
|
|
* |
|
23
|
|
|
* @var \Illuminate\Contracts\Logging\Log |
|
24
|
|
|
*/ |
|
25
|
|
|
protected $logger; |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* Create a new logger middleware. |
|
29
|
|
|
* |
|
30
|
|
|
* @param \Illuminate\Contracts\Logging\Log $logger |
|
31
|
|
|
* @param \Illuminate\Foundation\Application $app |
|
32
|
|
|
*/ |
|
33
|
|
|
public function __construct(Log $logger, Application $app) |
|
34
|
|
|
{ |
|
35
|
|
|
$this->app = $app; |
|
36
|
|
|
$this->logger = $logger; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* Write a message to the log whenever a command is received, handled or fails. |
|
41
|
|
|
* |
|
42
|
|
|
* @param object $command |
|
43
|
|
|
* @param callable $next |
|
44
|
|
|
* @return mixed |
|
45
|
|
|
* |
|
46
|
|
|
* @throws Exception |
|
47
|
|
|
* @throws Throwable |
|
48
|
|
|
*/ |
|
49
|
|
|
public function execute($command, callable $next) |
|
50
|
|
|
{ |
|
51
|
|
|
$levels = $this->app->config->get('tactician.log.levels'); |
|
52
|
|
|
$formatter = $this->app->make($this->app->config->get('tactician.log.formatter')); |
|
53
|
|
|
|
|
54
|
|
|
$this->log($levels['received'], $formatter->commandReceived($command)); |
|
55
|
|
|
|
|
56
|
|
|
try { |
|
57
|
|
|
$returnValue = $next($command); |
|
58
|
|
|
} catch (Exception $exception) { |
|
59
|
|
|
$this->log($levels['failed'], $formatter->commandFailed($command, $exception)); |
|
60
|
|
|
|
|
61
|
|
|
throw $exception; |
|
62
|
|
|
} catch (Throwable $exception) { |
|
|
|
|
|
|
63
|
|
|
$this->log($levels['failed'], $formatter->commandFailed($command, $exception)); |
|
64
|
|
|
|
|
65
|
|
|
throw $exception; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
$this->log($levels['handled'], $formatter->commandHandled($command)); |
|
69
|
|
|
|
|
70
|
|
|
return $returnValue; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
/** |
|
74
|
|
|
* Passes message and log level to logger instance. |
|
75
|
|
|
* |
|
76
|
|
|
* @param string $logLevel |
|
77
|
|
|
* @param string|null $message |
|
78
|
|
|
*/ |
|
79
|
|
|
protected function log($logLevel, $message) |
|
80
|
|
|
{ |
|
81
|
|
|
if (! is_null($message)) { |
|
82
|
|
|
$this->logger->log($logLevel, $message); |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
|