Skip to content

Commit

Permalink
Merge pull request #1 from kakadu-dev/ChangeMiceroservice
Browse files Browse the repository at this point in the history
added red colo for log, show memory leak log, run GC
  • Loading branch information
AntonMoisa authored Dec 6, 2020
2 parents 502cef7 + fc293e8 commit 6694c7d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/ConsoleLogDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public function __construct(bool $dummy = false)
/**
* @inheritDoc
*/
public function log(string $message, string $type, $id): void
public function log(string $message, string $type, $id = null): void
{
if ($this->dummy) {
return;
Expand All @@ -62,6 +62,10 @@ public function log(string $message, string $type, $id): void
case 3:
$color = "\e[34m"; // blue
break;

case 4:
$color = "\e[31m"; // red
break;
}

echo "$color $message \n";
Expand Down
33 changes: 33 additions & 0 deletions src/Microservice.php
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,8 @@ public function start(\Closure $clb): void
$request = $this->handleClientRequest();

while (true) {
$memoryBeginIteration = memory_get_usage(false);

$response = [];

if ($requestId = $request['id'] ?? null) {
Expand Down Expand Up @@ -278,6 +280,14 @@ public function start(\Closure $clb): void
$this->logDriver->log("<-- Response ({$rsp->getId()}): $rsp", 1, $rsp->getId());

$request = $this->handleClientRequest($rsp, false);

gc_collect_cycles();

$memoryLeak = (int) memory_get_usage(false) - (int) $memoryBeginIteration;
if ($memoryLeak > 0 ) {
$this->logDriver->log("!!! Your microservice has memory leak. Lost: {$this->getMemoryLeakSize($memoryLeak)}", 4);
}
unset($start, $memoryLeak);
}
}

Expand Down Expand Up @@ -341,4 +351,27 @@ protected function isDev(): bool

return substr('development', 0, strlen($env)) === $env;
}

/**
* convert memory leak size
*
* @param $bytes
*
* @return string
*/
function getMemoryLeakSize($bytes)
{
if ( $bytes < 1000 * 1024 ) {
return number_format( $bytes / 1024, 2 ) . " KB";
}
elseif ( $bytes < 1000 * 1048576 ) {
return number_format( $bytes / 1048576, 2 ) . " MB";
}
elseif ( $bytes < 1000 * 1073741824 ) {
return number_format( $bytes / 1073741824, 2 ) . " GB";
}
else {
return number_format( $bytes / 1099511627776, 2 ) . " TB";
}
}
}

0 comments on commit 6694c7d

Please sign in to comment.