functions.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCP\Log;
  8. use OC;
  9. use OCP\AppFramework\QueryException;
  10. use Psr\Log\LoggerInterface;
  11. use Psr\Log\NullLogger;
  12. use function class_exists;
  13. /**
  14. * Get a PSR logger
  15. *
  16. * Whenever possible, inject a logger into your classes instead of relying on
  17. * this helper function.
  18. *
  19. * @warning the returned logger implementation is not guaranteed to be the same
  20. * between two function calls. During early stages of the process you
  21. * might in fact get a noop implementation when Nextcloud isn't ready
  22. * to log. Therefore you MUST NOT cache the result of this function but
  23. * fetch a new logger for every log line you want to write.
  24. *
  25. * @param string|null $appId optional parameter to acquire the app-specific logger
  26. *
  27. * @return LoggerInterface
  28. * @since 24.0.0
  29. */
  30. function logger(?string $appId = null): LoggerInterface {
  31. /** @psalm-suppress TypeDoesNotContainNull false-positive, it may contain null if we are logging from initialization */
  32. if (!class_exists(OC::class) || OC::$server === null) {
  33. // If someone calls this log before Nextcloud is initialized, there is
  34. // no logging available. In that case we return a noop implementation
  35. // TODO: evaluate whether logging to error_log could be an alternative
  36. return new NullLogger();
  37. }
  38. if ($appId !== null) {
  39. try {
  40. $appContainer = OC::$server->getRegisteredAppContainer($appId);
  41. return $appContainer->get(LoggerInterface::class);
  42. } catch (QueryException $e) {
  43. // Ignore and return the server logger below
  44. }
  45. }
  46. try {
  47. return OC::$server->get(LoggerInterface::class);
  48. } catch (QueryException $e) {
  49. return new NullLogger();
  50. }
  51. }