You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
2.0 KiB

3 years ago
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  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 Symfony\Component\ErrorHandler;
  11. use Psr\Log\AbstractLogger;
  12. /**
  13. * A buffering logger that stacks logs for later.
  14. *
  15. * @author Nicolas Grekas <p@tchwork.com>
  16. */
  17. class BufferingLogger extends AbstractLogger
  18. {
  19. private $logs = [];
  20. public function log($level, $message, array $context = []): void
  21. {
  22. $this->logs[] = [$level, $message, $context];
  23. }
  24. public function cleanLogs(): array
  25. {
  26. $logs = $this->logs;
  27. $this->logs = [];
  28. return $logs;
  29. }
  30. public function __sleep()
  31. {
  32. throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
  33. }
  34. public function __wakeup()
  35. {
  36. throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  37. }
  38. public function __destruct()
  39. {
  40. foreach ($this->logs as [$level, $message, $context]) {
  41. if (false !== strpos($message, '{')) {
  42. foreach ($context as $key => $val) {
  43. if (null === $val || is_scalar($val) || (\is_object($val) && \is_callable([$val, '__toString']))) {
  44. $message = str_replace("{{$key}}", $val, $message);
  45. } elseif ($val instanceof \DateTimeInterface) {
  46. $message = str_replace("{{$key}}", $val->format(\DateTime::RFC3339), $message);
  47. } elseif (\is_object($val)) {
  48. $message = str_replace("{{$key}}", '[object '.\get_class($val).']', $message);
  49. } else {
  50. $message = str_replace("{{$key}}", '['.\gettype($val).']', $message);
  51. }
  52. }
  53. }
  54. error_log(sprintf('%s [%s] %s', date(\DateTime::RFC3339), $level, $message));
  55. }
  56. }
  57. }