-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathLoggerPlugin.php
80 lines (70 loc) · 2.97 KB
/
LoggerPlugin.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
<?php
namespace Http\Client\Common\Plugin;
use Http\Client\Common\Plugin;
use Http\Client\Exception;
use Http\Message\Formatter;
use Http\Message\Formatter\SimpleFormatter;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
/**
* Log request, response and exception for an HTTP Client.
*
* @author Joel Wurtz <[email protected]>
*/
final class LoggerPlugin implements Plugin
{
use VersionBridgePlugin;
private $logger;
private $formatter;
public function __construct(LoggerInterface $logger, Formatter $formatter = null)
{
$this->logger = $logger;
$this->formatter = $formatter ?: new SimpleFormatter();
}
protected function doHandleRequest(RequestInterface $request, callable $next, callable $first)
{
$start = hrtime(true) / 1E6;
$uid = uniqid('', true);
$this->logger->info(sprintf("Sending request:\n%s", $this->formatter->formatRequest($request)), ['uid' => $uid]);
return $next($request)->then(function (ResponseInterface $response) use ($start, $uid, $request) {
$milliseconds = (int) round(hrtime(true) / 1E6 - $start);
$formattedResponse = method_exists($this->formatter, 'formatResponseForRequest')
? $this->formatter->formatResponseForRequest($response, $request)
: $this->formatter->formatResponse($response);
$this->logger->info(
sprintf("Received response:\n%s", $formattedResponse),
[
'milliseconds' => $milliseconds,
'uid' => $uid,
]
);
return $response;
}, function (Exception $exception) use ($request, $start, $uid) {
$milliseconds = (int) round(hrtime(true) / 1E6 - $start);
if ($exception instanceof Exception\HttpException) {
$formattedResponse = method_exists($this->formatter, 'formatResponseForRequest')
? $this->formatter->formatResponseForRequest($exception->getResponse(), $exception->getRequest())
: $this->formatter->formatResponse($exception->getResponse());
$this->logger->error(
sprintf("Error:\n%s\nwith response:\n%s", $exception->getMessage(), $formattedResponse),
[
'exception' => $exception,
'milliseconds' => $milliseconds,
'uid' => $uid,
]
);
} else {
$this->logger->error(
sprintf("Error:\n%s\nwhen sending request:\n%s", $exception->getMessage(), $this->formatter->formatRequest($request)),
[
'exception' => $exception,
'milliseconds' => $milliseconds,
'uid' => $uid,
]
);
}
throw $exception;
});
}
}