Logger.php 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. <?php declare(strict_types=1);
  2. namespace mikemadisonweb\rabbitmq\components;
  3. use PhpAmqpLib\Message\AMQPMessage;
  4. use yii\helpers\Console;
  5. /**
  6. * @codeCoverageIgnore
  7. */
  8. class Logger
  9. {
  10. public $options;
  11. public function getOptions() : array
  12. {
  13. return $this->options;
  14. }
  15. /**
  16. * Print success message to console
  17. *
  18. * @param $queueName
  19. * @param $timeStart
  20. * @param $processFlag
  21. */
  22. public function printResult(string $queueName, $processFlag, $timeStart)
  23. {
  24. if (!$this->options['print_console']) {
  25. return;
  26. }
  27. if ($processFlag === ConsumerInterface::MSG_REQUEUE || false === $processFlag) {
  28. $messageFormat = '%s - Message from queue `%s` was not processed and sent back to queue! Execution time: %s %s';
  29. $color = Console::FG_RED;
  30. } elseif ($processFlag === ConsumerInterface::MSG_REJECT) {
  31. $messageFormat = '%s - Message from queue `%s` was not processed and dropped from queue! Execution time: %s %s';
  32. $color = Console::FG_RED;
  33. } else {
  34. $messageFormat = '%s - Message from queue `%s` consumed successfully! Execution time: %s %s';
  35. $color = Console::FG_GREEN;
  36. }
  37. $curDate = date('Y-m-d H:i:s');
  38. $execTime = $this->getExecutionTime($timeStart);
  39. $memory = $this->getMemory();
  40. $consoleMessage = sprintf($messageFormat, $curDate, $queueName, $execTime, $memory);
  41. $this->printInfo($consoleMessage, $color);
  42. }
  43. /**
  44. * @param \Exception $e
  45. */
  46. public function printError(\Exception $e)
  47. {
  48. if (!$this->options['print_console']) {
  49. return;
  50. }
  51. $color = Console::FG_RED;
  52. $consoleMessage = sprintf('Error: %s File: %s Line: %s', $e->getMessage(), $e->getFile(), $e->getLine());
  53. $this->printInfo($consoleMessage, $color);
  54. }
  55. /**
  56. * Log message using standard Yii logger
  57. * @param string $title
  58. * @param AMQPMessage $msg
  59. * @param array $options
  60. */
  61. public function log(string $title, AMQPMessage $msg, array $options)
  62. {
  63. if (!$this->options['log']) {
  64. return;
  65. }
  66. $extra['execution_time'] = isset($options['timeStart']) ? $this->getExecutionTime($options['timeStart']) : null;
  67. $extra['return_code'] = $options['processFlag'] ?? null;
  68. $extra['memory'] = isset($options['memory']) ? $this->getMemory() : null;
  69. $extra['routing_key'] = $options['routingKey'] ?? null;
  70. $extra['queue'] = $options['queue'] ?? null;
  71. $extra['exchange'] = $options['exchange'] ?? null;
  72. \Yii::info([
  73. 'info' => $title,
  74. 'amqp' => [
  75. 'body' => $msg->getBody(),
  76. 'headers' => $msg->has('application_headers') ? $msg->get('application_headers')->getNativeData() : null,
  77. 'extra' => $extra,
  78. ],
  79. ], $this->options['category']);
  80. }
  81. /**
  82. * Log error message using standard Yii logger
  83. * @param \Throwable $e
  84. * @param AMQPMessage $msg
  85. */
  86. public function logError(\Throwable $e, AMQPMessage $msg)
  87. {
  88. if (!$this->options['log']) {
  89. return;
  90. }
  91. \Yii::error([
  92. 'msg' => $e->getMessage(),
  93. 'amqp' => [
  94. 'message' => $msg->getBody(),
  95. 'stacktrace' => $e->getTraceAsString(),
  96. ],
  97. ], $this->options['category']);
  98. }
  99. /**
  100. * Print message to STDOUT
  101. * @param $message
  102. * @param $color
  103. * @return bool|int
  104. */
  105. public function printInfo($message, $color = Console::FG_YELLOW)
  106. {
  107. if (Console::streamSupportsAnsiColors(\STDOUT)) {
  108. $message = Console::ansiFormat($message, [$color]);
  109. }
  110. return Console::output($message);
  111. }
  112. /**
  113. * @param $timeStart
  114. * @param int $round
  115. * @return string
  116. */
  117. protected function getExecutionTime($timeStart, int $round = 3) : string
  118. {
  119. return (string)round(microtime(true) - $timeStart, $round) . 's';
  120. }
  121. /**
  122. * Get either script memory usage or free system memory info
  123. * @return string
  124. */
  125. protected function getMemory() : string
  126. {
  127. if ($this->options['system_memory']) {
  128. return $this->getSystemFreeMemory();
  129. }
  130. return 'Memory usage: ' . $this->getMemoryDiff();
  131. }
  132. /**
  133. * Get memory usage in human readable format
  134. * @return string
  135. */
  136. protected function getMemoryDiff() : string
  137. {
  138. $memory = memory_get_usage(true);
  139. if(0 === $memory) {
  140. return '0b';
  141. }
  142. $unit = ['b','kb','mb','gb','tb','pb'];
  143. return @round($memory/ (1024 ** ($i = floor(log($memory, 1024)))),2).' '.$unit[$i];
  144. }
  145. /**
  146. * Free system memory
  147. *
  148. * @return string
  149. */
  150. protected function getSystemFreeMemory() : string
  151. {
  152. $data = explode("\n", trim(file_get_contents('/proc/meminfo')));
  153. return sprintf(
  154. '%s, %s',
  155. preg_replace('/\s+/', ' ', $data[0]),
  156. preg_replace('/\s+/', ' ', $data[1])
  157. );
  158. }
  159. }