DbalLogger.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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\Bridge\Doctrine\Logger;
  11. use Doctrine\DBAL\Logging\SQLLogger;
  12. use Psr\Log\LoggerInterface;
  13. use Symfony\Component\Stopwatch\Stopwatch;
  14. /**
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class DbalLogger implements SQLLogger
  18. {
  19. const MAX_STRING_LENGTH = 32;
  20. const BINARY_DATA_VALUE = '(binary value)';
  21. protected $logger;
  22. protected $stopwatch;
  23. public function __construct(LoggerInterface $logger = null, Stopwatch $stopwatch = null)
  24. {
  25. $this->logger = $logger;
  26. $this->stopwatch = $stopwatch;
  27. }
  28. /**
  29. * {@inheritdoc}
  30. */
  31. public function startQuery($sql, array $params = null, array $types = null)
  32. {
  33. if (null !== $this->stopwatch) {
  34. $this->stopwatch->start('doctrine', 'doctrine');
  35. }
  36. if (null !== $this->logger) {
  37. $this->log($sql, null === $params ? array() : $this->normalizeParams($params));
  38. }
  39. }
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function stopQuery()
  44. {
  45. if (null !== $this->stopwatch) {
  46. $this->stopwatch->stop('doctrine');
  47. }
  48. }
  49. /**
  50. * Logs a message.
  51. *
  52. * @param string $message A message to log
  53. * @param array $params The context
  54. */
  55. protected function log($message, array $params)
  56. {
  57. $this->logger->debug($message, $params);
  58. }
  59. private function normalizeParams(array $params)
  60. {
  61. foreach ($params as $index => $param) {
  62. // normalize recursively
  63. if (\is_array($param)) {
  64. $params[$index] = $this->normalizeParams($param);
  65. continue;
  66. }
  67. if (!\is_string($params[$index])) {
  68. continue;
  69. }
  70. // non utf-8 strings break json encoding
  71. if (!preg_match('//u', $params[$index])) {
  72. $params[$index] = self::BINARY_DATA_VALUE;
  73. continue;
  74. }
  75. // detect if the too long string must be shorten
  76. if (self::MAX_STRING_LENGTH < mb_strlen($params[$index], 'UTF-8')) {
  77. $params[$index] = mb_substr($params[$index], 0, self::MAX_STRING_LENGTH - 6, 'UTF-8').' [...]';
  78. continue;
  79. }
  80. }
  81. return $params;
  82. }
  83. }