1
0

QueryLogger.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Lukas Reschke <lukas@statuscode.ch>
  6. * @author Morris Jobke <hey@morrisjobke.de>
  7. * @author Piotr Mrówczyński <mrow4a@yahoo.com>
  8. * @author Robin Appelman <robin@icewind.nl>
  9. *
  10. * @license AGPL-3.0
  11. *
  12. * This code is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU Affero General Public License, version 3,
  14. * as published by the Free Software Foundation.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU Affero General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public License, version 3,
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>
  23. *
  24. */
  25. namespace OC\Diagnostics;
  26. use OCP\Cache\CappedMemoryCache;
  27. use OCP\Diagnostics\IQueryLogger;
  28. class QueryLogger implements IQueryLogger {
  29. protected int $index = 0;
  30. protected ?Query $activeQuery = null;
  31. /** @var CappedMemoryCache<Query> */
  32. protected CappedMemoryCache $queries;
  33. /**
  34. * QueryLogger constructor.
  35. */
  36. public function __construct() {
  37. $this->queries = new CappedMemoryCache(1024);
  38. }
  39. /**
  40. * @var bool - Module needs to be activated by some app
  41. */
  42. private $activated = false;
  43. /**
  44. * @inheritdoc
  45. */
  46. public function startQuery($sql, ?array $params = null, ?array $types = null) {
  47. if ($this->activated) {
  48. $this->activeQuery = new Query($sql, $params, microtime(true), $this->getStack());
  49. }
  50. }
  51. private function getStack() {
  52. $stack = debug_backtrace();
  53. array_shift($stack);
  54. array_shift($stack);
  55. array_shift($stack);
  56. return $stack;
  57. }
  58. /**
  59. * @inheritdoc
  60. */
  61. public function stopQuery() {
  62. if ($this->activated && $this->activeQuery) {
  63. $this->activeQuery->end(microtime(true));
  64. $this->queries[(string)$this->index] = $this->activeQuery;
  65. $this->index++;
  66. $this->activeQuery = null;
  67. }
  68. }
  69. /**
  70. * @inheritdoc
  71. */
  72. public function getQueries() {
  73. return $this->queries->getData();
  74. }
  75. /**
  76. * @inheritdoc
  77. */
  78. public function activate() {
  79. $this->activated = true;
  80. }
  81. }