MemoryProcessor.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Processor;
  11. /**
  12. * Some methods that are common for all memory processors
  13. *
  14. * @author Rob Jensen
  15. */
  16. abstract class MemoryProcessor implements ProcessorInterface
  17. {
  18. /**
  19. * @var bool If true, get the real size of memory allocated from system. Else, only the memory used by emalloc() is reported.
  20. */
  21. protected $realUsage;
  22. /**
  23. * @var bool If true, then format memory size to human readable string (MB, KB, B depending on size)
  24. */
  25. protected $useFormatting;
  26. /**
  27. * @param bool $realUsage Set this to true to get the real size of memory allocated from system.
  28. * @param bool $useFormatting If true, then format memory size to human readable string (MB, KB, B depending on size)
  29. */
  30. public function __construct(bool $realUsage = true, bool $useFormatting = true)
  31. {
  32. $this->realUsage = $realUsage;
  33. $this->useFormatting = $useFormatting;
  34. }
  35. /**
  36. * Formats bytes into a human readable string if $this->useFormatting is true, otherwise return $bytes as is
  37. *
  38. * @return string|int Formatted string if $this->useFormatting is true, otherwise return $bytes as int
  39. */
  40. protected function formatBytes(int $bytes)
  41. {
  42. if (!$this->useFormatting) {
  43. return $bytes;
  44. }
  45. if ($bytes > 1024 * 1024) {
  46. return round($bytes / 1024 / 1024, 2).' MB';
  47. } elseif ($bytes > 1024) {
  48. return round($bytes / 1024, 2).' KB';
  49. }
  50. return $bytes . ' B';
  51. }
  52. }