Skip to content

Commit

Permalink
Add port in url for trace and logger messages (#1126)
Browse files Browse the repository at this point in the history
* Added port in url for trace and logger messages

* Fixed CS issue
  • Loading branch information
ezimuel committed Apr 21, 2021
1 parent bcbc427 commit f0bc440
Show file tree
Hide file tree
Showing 2 changed files with 129 additions and 14 deletions.
46 changes: 32 additions & 14 deletions src/Elasticsearch/Connections/Connection.php
Expand Up @@ -394,13 +394,16 @@ public function logWarning(array $request, array $response): void
*/
public function logRequestSuccess(array $request, array $response): void
{
$port = $request['client']['curl'][CURLOPT_PORT] ?? $response['transfer_stats']['primary_port'] ?? '';
$uri = $this->addPortInUrl($response['effective_url'], (int) $port);

$this->log->debug('Request Body', array($request['body']));
$this->log->info(
'Request Success:',
array(
'method' => $request['http_method'],
'uri' => $response['effective_url'],
'port' => $response['transfer_stats']['primary_port'] ?? '',
'uri' => $uri,
'port' => $port,
'headers' => $request['headers'],
'HTTP code' => $response['status'],
'duration' => $response['transfer_stats']['total_time'],
Expand All @@ -409,14 +412,15 @@ public function logRequestSuccess(array $request, array $response): void
$this->log->debug('Response', array($response['body']));

// Build the curl command for Trace.
$curlCommand = $this->buildCurlCommand($request['http_method'], $response['effective_url'], $request['body']);
$curlCommand = $this->buildCurlCommand($request['http_method'], $uri, $request['body']);
$this->trace->info($curlCommand);
$this->trace->debug(
'Response:',
array(
'response' => $response['body'],
'method' => $request['http_method'],
'uri' => $response['effective_url'],
'uri' => $uri,
'port' => $port,
'HTTP code' => $response['status'],
'duration' => $response['transfer_stats']['total_time'],
)
Expand All @@ -434,14 +438,16 @@ public function logRequestSuccess(array $request, array $response): void
*/
public function logRequestFail(array $request, array $response, \Exception $exception): void
{
$this->log->debug('Request Body', array($request['body']));
$port = $request['client']['curl'][CURLOPT_PORT] ?? $response['transfer_stats']['primary_port'] ?? '';
$uri = $this->addPortInUrl($response['effective_url'], (int) $port);

$this->log->debug('Request Body', array($request['body']));
$this->log->warning(
'Request Failure:',
array(
'method' => $request['http_method'],
'uri' => $response['effective_url'],
'port' => $response['transfer_stats']['primary_port'] ?? '',
'uri' => $uri,
'port' => $port,
'headers' => $request['headers'],
'HTTP code' => $response['status'],
'duration' => $response['transfer_stats']['total_time'],
Expand All @@ -451,14 +457,15 @@ public function logRequestFail(array $request, array $response, \Exception $exce
$this->log->warning('Response', array($response['body']));

// Build the curl command for Trace.
$curlCommand = $this->buildCurlCommand($request['http_method'], $response['effective_url'], $request['body']);
$curlCommand = $this->buildCurlCommand($request['http_method'], $uri, $request['body']);
$this->trace->info($curlCommand);
$this->trace->debug(
'Response:',
array(
'response' => $response,
'method' => $request['http_method'],
'uri' => $response['effective_url'],
'uri' => $uri,
'port' => $port,
'HTTP code' => $response['status'],
'duration' => $response['transfer_stats']['total_time'],
)
Expand Down Expand Up @@ -624,19 +631,30 @@ private function getOSVersion(): string
return $this->OSVersion;
}

/**
* Add the port value in the URL if not present
*/
private function addPortInUrl(string $uri, int $port): string
{
if (strpos($uri, ':', 7) !== false) {
return $uri;
}
return preg_replace('#([^/])/([^/])#', sprintf("$1:%s/$2", $port), $uri, 1);
}

/**
* Construct a string cURL command
*/
private function buildCurlCommand(string $method, string $uri, ?string $body): string
private function buildCurlCommand(string $method, string $url, ?string $body): string
{
if (strpos($uri, '?') === false) {
$uri .= '?pretty=true';
if (strpos($url, '?') === false) {
$url .= '?pretty=true';
} else {
str_replace('?', '?pretty=true', $uri);
str_replace('?', '?pretty=true', $url);
}

$curlCommand = 'curl -X' . strtoupper($method);
$curlCommand .= " '" . $uri . "'";
$curlCommand .= " '" . $url . "'";

if (isset($body) === true && $body !== '') {
$curlCommand .= " -d '" . $body . "'";
Expand Down
97 changes: 97 additions & 0 deletions tests/Elasticsearch/Tests/Connections/ConnectionTest.php
Expand Up @@ -24,6 +24,8 @@
use Elasticsearch\Connections\Connection;
use Elasticsearch\Serializers\SerializerInterface;
use Elasticsearch\Serializers\SmartSerializer;
use Elasticsearch\Tests\ClientBuilder\ArrayLogger;
use Exception;
use Psr\Log\LoggerInterface;
use ReflectionClass;

Expand Down Expand Up @@ -452,4 +454,99 @@ public function testParametersAreSent()

$this->assertEquals('/?foo=true&baz=false&bar=baz', $request['uri']);
}

public function testPortInUrlWhenLogRequestSuccess()
{
$logger = new ArrayLogger();
$trace = new ArrayLogger();

$connection = new Connection(
ClientBuilder::defaultHandler(),
[
'host' => 'localhost',
'port' => 9200,
'scheme' => 'http',
'path' => '/info'
],
[],
$this->serializer,
$logger,
$trace
);
$request = [
'body' => '{}',
'http_method' => 'GET',
'headers' => [
'User-Agent: Testing'
]
];
$response = [
'effective_url' => 'http://localhost/info',
'status' => 200,
'transfer_stats' => [
'primary_port' => 9200,
'total_time' => 1
],
'body' => '{}'
];
$connection->logRequestSuccess($request, $response);
// Check for localhost:9200 in trace
foreach ($trace->output as $row) {
$this->assertStringContainsString('localhost:9200', $row);
}
// Check for localhost:9200 in logger
foreach ($logger->output as $row) {
if (false !== strpos('info: Request Success', $row)) {
$this->assertStringContainsString('localhost:9200', $row);
}
}
}

public function testPortInLogUrlWhenLogRequestFail()
{
$logger = new ArrayLogger();
$trace = new ArrayLogger();

$connection = new Connection(
ClientBuilder::defaultHandler(),
[
'host' => 'localhost',
'port' => 9200,
'scheme' => 'http',
'path' => '/info'
],
[],
$this->serializer,
$logger,
$trace
);
$request = [
'body' => '{}',
'http_method' => 'GET',
'headers' => [
'User-Agent: Testing'
]
];
$response = [
'effective_url' => 'http://localhost/info',
'status' => 400,
'transfer_stats' => [
'primary_port' => 9200,
'total_time' => 1
],
'body' => '{}'
];
$connection->logRequestFail($request, $response, new Exception());

// Check for localhost:9200 in trace
foreach ($trace->output as $row) {
$this->assertStringContainsString('localhost:9200', $row);
}
// Check for localhost:9200 in logger
foreach ($logger->output as $row) {
if (false !== strpos('warning: Request Failure:', $row)) {
$this->assertStringContainsString('localhost:9200', $row);
}
}
}
}

0 comments on commit f0bc440

Please sign in to comment.