BufferingLogger.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. }