LogFormatter.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace AlibabaCloud\Client\Log;
  3. use DateTime;
  4. use Exception;
  5. use DateTimeZone;
  6. use GuzzleHttp\MessageFormatter;
  7. use Psr\Http\Message\RequestInterface;
  8. use Psr\Http\Message\ResponseInterface;
  9. /**
  10. * @deprecated Use GuzzleHttp\MessageFormatter.
  11. * Class LogFormatter
  12. *
  13. * @package AlibabaCloud\Client\Log
  14. */
  15. class LogFormatter
  16. {
  17. /**
  18. * @var float
  19. */
  20. private static $logStartTime = 0;
  21. /**
  22. * @var DateTime
  23. */
  24. private static $ts;
  25. /** @var string Template used to format log messages */
  26. public $template;
  27. /**
  28. * @param string $template Log message template
  29. *
  30. * @throws Exception
  31. */
  32. public function __construct($template)
  33. {
  34. parent::__construct($template);
  35. self::$logStartTime = microtime(true);
  36. $this->template = $template;
  37. $timezone = new DateTimeZone(date_default_timezone_get() ?: 'UTC');
  38. if (PHP_VERSION_ID < 70100) {
  39. self::$ts = DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true)), $timezone);
  40. } else {
  41. self::$ts = new DateTime(null, $timezone);
  42. }
  43. }
  44. /**
  45. * Returns a formatted message string.
  46. *
  47. * @param RequestInterface $request Request that was sent
  48. * @param ResponseInterface $response Response that was received
  49. * @param Exception $error Exception that was received
  50. *
  51. * @return string
  52. */
  53. public function format(
  54. RequestInterface $request,
  55. ResponseInterface $response = null,
  56. Exception $error = null
  57. ) {
  58. $this->template = str_replace('{pid}', getmypid(), $this->template);
  59. $this->template = str_replace('{cost}', self::getCost(), $this->template);
  60. $this->template = str_replace('{start_time}', self::$ts->format('Y-m-d H:i:s.u'), $this->template);
  61. return (new MessageFormatter($this->template))->format($request, $response, $error);
  62. }
  63. /**
  64. * @return float|mixed
  65. */
  66. private static function getCost()
  67. {
  68. return microtime(true) - self::$logStartTime;
  69. }
  70. }