|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Request logging |
|
4
|
|
|
* User: moyo |
|
5
|
|
|
* Date: 12/10/2017 |
|
6
|
|
|
* Time: 6:29 PM |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace Carno\HRPC\Handlers; |
|
10
|
|
|
|
|
11
|
|
|
use Carno\Chain\Layered; |
|
12
|
|
|
use Carno\Coroutine\Context; |
|
13
|
|
|
use Carno\RPC\Protocol\Request; |
|
14
|
|
|
use Carno\RPC\Protocol\Response; |
|
15
|
|
|
use Throwable; |
|
16
|
|
|
|
|
17
|
|
|
class RequestLogger implements Layered |
|
18
|
|
|
{ |
|
19
|
|
|
/** |
|
20
|
|
|
* ctx vars |
|
21
|
|
|
*/ |
|
22
|
|
|
private const REQUEST = 'log-request'; |
|
23
|
|
|
private const START_TIME = 'log-start'; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @param Request $request |
|
27
|
|
|
* @param Context $ctx |
|
28
|
|
|
* @return Request |
|
29
|
|
|
*/ |
|
30
|
|
|
public function inbound($request, Context $ctx) : Request |
|
31
|
|
|
{ |
|
32
|
|
|
$ctx->set(self::REQUEST, $request); |
|
33
|
|
|
$ctx->set(self::START_TIME, microtime(true)); |
|
34
|
|
|
return $request; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* @param Response $response |
|
39
|
|
|
* @param Context $ctx |
|
40
|
|
|
* @return Response |
|
41
|
|
|
*/ |
|
42
|
|
|
public function outbound($response, Context $ctx) : Response |
|
43
|
|
|
{ |
|
44
|
|
|
$this->requestFIN($ctx, null); |
|
45
|
|
|
return $response; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* @param Throwable $e |
|
50
|
|
|
* @param Context $ctx |
|
51
|
|
|
* @throws Throwable |
|
52
|
|
|
*/ |
|
53
|
|
|
public function exception(Throwable $e, Context $ctx) : void |
|
54
|
|
|
{ |
|
55
|
|
|
$this->requestFIN($ctx, $e); |
|
56
|
|
|
throw $e; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* @param Context $ctx |
|
61
|
|
|
* @param Throwable $e |
|
62
|
|
|
*/ |
|
63
|
|
|
private function requestFIN(Context $ctx, Throwable $e = null) : void |
|
64
|
|
|
{ |
|
65
|
|
|
/** |
|
66
|
|
|
* @var Request $rpc |
|
67
|
|
|
* @var float $start |
|
68
|
|
|
*/ |
|
69
|
|
|
$rpc = $ctx->get(self::REQUEST); |
|
70
|
|
|
$start = $ctx->get(self::START_TIME); |
|
71
|
|
|
|
|
72
|
|
|
$meta = [ |
|
73
|
|
|
'id' => $rpc ? $rpc->identify() : 'unknown', |
|
|
|
|
|
|
74
|
|
|
'cost' => $start ? intval((microtime(true) - $start) * 1000) : 0, |
|
75
|
|
|
]; |
|
76
|
|
|
|
|
77
|
|
|
if ($e) { |
|
78
|
|
|
$meta = array_merge($meta, [ |
|
79
|
|
|
'err' => get_class($e) . '::' . $e->getMessage(), |
|
80
|
|
|
'file' => $e->getFile(), |
|
81
|
|
|
'line' => $e->getLine(), |
|
82
|
|
|
]); |
|
83
|
|
|
logger('hrpc')->notice('Request failed', $meta); |
|
84
|
|
|
} else { |
|
85
|
|
|
logger('hrpc')->debug('Request finished', $meta); |
|
86
|
|
|
} |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|