LogTrait.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace AlibabaCloud\Client\Traits;
  3. use DateTime;
  4. use DateTimeZone;
  5. use Exception;
  6. use Psr\Log\LoggerInterface;
  7. /**
  8. * Trait LogTrait
  9. *
  10. * @package AlibabaCloud\Client\Traits
  11. */
  12. trait LogTrait
  13. {
  14. /**
  15. * @var LoggerInterface
  16. */
  17. private static $logger;
  18. /**
  19. * @var float
  20. */
  21. private static $logStartTime = 0;
  22. /**
  23. * @var string
  24. */
  25. private static $logFormat;
  26. /**
  27. * @var DateTime
  28. */
  29. private static $ts;
  30. /**
  31. * @return LoggerInterface
  32. */
  33. public static function getLogger()
  34. {
  35. return self::$logger;
  36. }
  37. /**
  38. * @param LoggerInterface $logger
  39. *
  40. * @throws Exception
  41. */
  42. public static function setLogger(LoggerInterface $logger)
  43. {
  44. self::$logger = $logger;
  45. self::$logStartTime = microtime(true);
  46. $timezone = new DateTimeZone(date_default_timezone_get() ?: 'UTC');
  47. if (PHP_VERSION_ID < 70100) {
  48. self::$ts = DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true)), $timezone);
  49. } else {
  50. self::$ts = new DateTime(null, $timezone);
  51. }
  52. }
  53. /**
  54. * @return string
  55. */
  56. public static function getLogFormat()
  57. {
  58. $template = self::$logFormat
  59. ?: '"{method} {uri} HTTP/{version}" {code} {cost} {hostname} {pid}';
  60. return str_replace(
  61. ['{pid}', '{cost}', '{start_time}'],
  62. [getmypid(), self::getCost(), self::$ts->format('Y-m-d H:i:s.u')],
  63. $template
  64. );
  65. }
  66. /**
  67. * Apache Common Log Format.
  68. *
  69. * @param string $formatter
  70. *
  71. * @link http://httpd.apache.org/docs/2.4/logs.html#common
  72. * @see \GuzzleHttp\MessageFormatter
  73. */
  74. public static function setLogFormat($formatter)
  75. {
  76. self::$logFormat = $formatter;
  77. }
  78. /**
  79. * @return float|mixed
  80. */
  81. private static function getCost()
  82. {
  83. return microtime(true) - self::$logStartTime;
  84. }
  85. }