1
0

QueryLogger.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Diagnostics;
  8. use OCP\Cache\CappedMemoryCache;
  9. use OCP\Diagnostics\IQueryLogger;
  10. class QueryLogger implements IQueryLogger {
  11. protected int $index = 0;
  12. protected ?Query $activeQuery = null;
  13. /** @var CappedMemoryCache<Query> */
  14. protected CappedMemoryCache $queries;
  15. /**
  16. * QueryLogger constructor.
  17. */
  18. public function __construct() {
  19. $this->queries = new CappedMemoryCache(1024);
  20. }
  21. /**
  22. * @var bool - Module needs to be activated by some app
  23. */
  24. private $activated = false;
  25. /**
  26. * @inheritdoc
  27. */
  28. public function startQuery($sql, ?array $params = null, ?array $types = null) {
  29. if ($this->activated) {
  30. $this->activeQuery = new Query($sql, $params, microtime(true), $this->getStack());
  31. }
  32. }
  33. private function getStack() {
  34. $stack = debug_backtrace();
  35. array_shift($stack);
  36. array_shift($stack);
  37. array_shift($stack);
  38. return $stack;
  39. }
  40. /**
  41. * @inheritdoc
  42. */
  43. public function stopQuery() {
  44. if ($this->activated && $this->activeQuery) {
  45. $this->activeQuery->end(microtime(true));
  46. $this->queries[(string)$this->index] = $this->activeQuery;
  47. $this->index++;
  48. $this->activeQuery = null;
  49. }
  50. }
  51. /**
  52. * @inheritdoc
  53. */
  54. public function getQueries() {
  55. return $this->queries->getData();
  56. }
  57. /**
  58. * @inheritdoc
  59. */
  60. public function activate() {
  61. $this->activated = true;
  62. }
  63. }