1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace GBProd\ElasticaBundle\Elastica; |
4
|
|
|
|
5
|
|
|
use Elastica\Client as BaseClient; |
6
|
|
|
use Elastica\Request; |
7
|
|
|
use GBProd\ElasticaBundle\Logger\ElasticaLogger; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Extends the default Elastica client to provide logging for errors that occur |
11
|
|
|
* during communication with ElasticSearch. |
12
|
|
|
* |
13
|
|
|
* @author Gordon Franke <[email protected]> |
14
|
|
|
*/ |
15
|
|
|
class Client extends BaseClient |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @param string $path |
19
|
|
|
* @param string $method |
20
|
|
|
* @param array $data |
21
|
|
|
* @param array $query |
22
|
|
|
* |
23
|
|
|
* @return \Elastica\Response |
24
|
|
|
*/ |
25
|
1 |
|
public function request($path, $method = Request::GET, $data = array(), array $query = array()) |
26
|
|
|
{ |
27
|
1 |
|
$start = microtime(true); |
28
|
1 |
|
$response = parent::request($path, $method, $data, $query); |
29
|
1 |
|
$responseData = $response->getData(); |
30
|
|
|
|
31
|
1 |
|
if (isset($responseData['took']) && isset($responseData['hits'])) { |
32
|
1 |
|
$this->logQuery($path, $method, $data, $query, $start, $response->getEngineTime(), $responseData['hits']['total']); |
|
|
|
|
33
|
1 |
|
} else { |
34
|
|
|
$this->logQuery($path, $method, $data, $query, $start, 0, 0); |
35
|
|
|
} |
36
|
|
|
|
37
|
1 |
|
return $response; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Log the query if we have an instance of ElasticaLogger. |
42
|
|
|
* |
43
|
|
|
* @param string $path |
44
|
|
|
* @param string $method |
45
|
|
|
* @param array $data |
46
|
|
|
* @param array $query |
47
|
|
|
* @param int $start |
48
|
|
|
*/ |
49
|
1 |
|
private function logQuery($path, $method, $data, array $query, $start, $engineMS = 0, $itemCount = 0) |
50
|
|
|
{ |
51
|
1 |
|
if (!$this->_logger or !$this->_logger instanceof ElasticaLogger) { |
|
|
|
|
52
|
|
|
return; |
53
|
|
|
} |
54
|
|
|
|
55
|
1 |
|
$time = microtime(true) - $start; |
56
|
1 |
|
$connection = $this->getLastRequest()->getConnection(); |
57
|
|
|
|
58
|
|
|
$connection_array = array( |
59
|
1 |
|
'host' => $connection->getHost(), |
60
|
1 |
|
'port' => $connection->getPort(), |
61
|
1 |
|
'transport' => $connection->getTransport(), |
62
|
1 |
|
'headers' => $connection->hasConfig('headers') ? $connection->getConfig('headers') : array(), |
63
|
1 |
|
); |
64
|
|
|
|
65
|
1 |
|
$this->_logger->logQuery($path, $method, $data, $time, $connection_array, $query, $engineMS, $itemCount); |
66
|
1 |
|
} |
67
|
|
|
} |
68
|
|
|
|
Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.