- Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathLogMiddleware.php
More file actions
75 lines (56 loc) · 2.41 KB
/
LogMiddleware.php
File metadata and controls
75 lines (56 loc) · 2.41 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
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
<?php
namespace EightPoints\Bundle\GuzzleBundle\Middleware;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\MessageFormatter;
use EightPoints\Bundle\GuzzleBundle\Log\LoggerInterface;
class LogMiddleware
{
/** @var \GuzzleHttp\MessageFormatter */
protected $formatter;
/** @var \EightPoints\Bundle\GuzzleBundle\Log\LoggerInterface */
protected $logger;
/**
* @param \EightPoints\Bundle\GuzzleBundle\Log\LoggerInterface $logger
* @param \GuzzleHttp\MessageFormatter $formatter
*/
public function __construct(LoggerInterface $logger, MessageFormatter $formatter)
{
$this->logger = $logger;
$this->formatter = $formatter;
}
/**
* Logging each Request
*
* @return \Closure
*/
public function log() : \Closure
{
$logger = $this->logger;
$formatter = $this->formatter;
return function (callable $handler) use ($logger, $formatter) {
return function ($request, array $options) use ($handler, $logger, $formatter) {
// generate id that will be used to supplement the log with information
$requestId = uniqid('eight_points_guzzle_');
// initial registration of log
$logger->info('', compact('request', 'requestId'));
// this id will be used by RequestTimeMiddleware
$options['request_id'] = $requestId;
return $handler($request, $options)->then(
function ($response) use ($logger, $request, $formatter, $requestId) {
$message = $formatter->format($request, $response);
$context = compact('request', 'response', 'requestId');
$logger->info($message, $context);
return $response;
},
function ($reason) use ($logger, $request, $formatter, $requestId) {
$response = $reason instanceof RequestException ? $reason->getResponse() : null;
$message = $formatter->format($request, $response, $reason);
$context = compact('request', 'response', 'requestId');
$logger->notice($message, $context);
return \GuzzleHttp\Promise\Create::rejectionFor($reason);
}
);
};
};
}
}