forked from php-http/logger-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoggerPlugin.php
More file actions
83 lines (75 loc) · 2.96 KB
/
LoggerPlugin.php
File metadata and controls
83 lines (75 loc) · 2.96 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
76
77
78
79
80
81
82
83
<?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 Http\Promise\Promise;
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 <joel.wurtz@gmail.com>
*/
final readonly class LoggerPlugin implements Plugin
{
private Formatter $formatter;
public function __construct(
private LoggerInterface $logger,
?Formatter $formatter = null
) {
$this->formatter = $formatter ?? new SimpleFormatter();
}
public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise
{
$start = hrtime(true) / 1E6;
$uid = uniqid('', true);
$this->logger->info(
sprintf("Sending request:\n%s", $this->formatter->formatRequest($request)),
[
'uid' => $uid,
'uri' => (string) $request->getUri(),
]
);
return $next($request)->then(function (ResponseInterface $response) use ($start, $uid, $request) {
$milliseconds = (int) round(hrtime(true) / 1E6 - $start);
$formattedResponse = $this->formatter->formatResponseForRequest($response, $request);
$this->logger->info(
sprintf("Received response:\n%s", $formattedResponse),
[
'milliseconds' => $milliseconds,
'uid' => $uid,
'uri' => (string) $request->getUri(),
]
);
return $response;
}, function (Exception $exception) use ($request, $start, $uid) {
$milliseconds = (int) round(hrtime(true) / 1E6 - $start);
if ($exception instanceof Exception\HttpException) {
$formattedResponse = $this->formatter->formatResponseForRequest($exception->getResponse(), $exception->getRequest());
$this->logger->error(
sprintf("Error:\n%s\nwith response:\n%s", $exception->getMessage(), $formattedResponse),
[
'exception' => $exception,
'milliseconds' => $milliseconds,
'uid' => $uid,
'uri' => (string) $request->getUri(),
]
);
} 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,
'uri' => (string) $request->getUri(),
]
);
}
throw $exception;
});
}
}