Ingen beskrivning

BufferingLogger.php 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. /**
  31. * @return array
  32. */
  33. public function __sleep()
  34. {
  35. throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
  36. }
  37. public function __wakeup()
  38. {
  39. throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  40. }
  41. public function __destruct()
  42. {
  43. foreach ($this->logs as [$level, $message, $context]) {
  44. if (false !== strpos($message, '{')) {
  45. foreach ($context as $key => $val) {
  46. if (null === $val || is_scalar($val) || (\is_object($val) && \is_callable([$val, '__toString']))) {
  47. $message = str_replace("{{$key}}", $val, $message);
  48. } elseif ($val instanceof \DateTimeInterface) {
  49. $message = str_replace("{{$key}}", $val->format(\DateTime::RFC3339), $message);
  50. } elseif (\is_object($val)) {
  51. $message = str_replace("{{$key}}", '[object '.\get_class($val).']', $message);
  52. } else {
  53. $message = str_replace("{{$key}}", '['.\gettype($val).']', $message);
  54. }
  55. }
  56. }
  57. error_log(sprintf('%s [%s] %s', date(\DateTime::RFC3339), $level, $message));
  58. }
  59. }
  60. }