functions.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * @copyright 2022 Christoph Wurst <christoph@winzerhof-wurst.at>
  5. *
  6. * @author 2022 Christoph Wurst <christoph@winzerhof-wurst.at>
  7. *
  8. * @license GNU AGPL version 3 or any later version
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as
  12. * published by the Free Software Foundation, either version 3 of the
  13. * License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. */
  23. namespace OCP\Log;
  24. use OC;
  25. use OCP\AppFramework\QueryException;
  26. use Psr\Log\LoggerInterface;
  27. use Psr\Log\NullLogger;
  28. use function class_exists;
  29. /**
  30. * Get a PSR logger
  31. *
  32. * Whenever possible, inject a logger into your classes instead of relying on
  33. * this helper function.
  34. *
  35. * @warning the returned logger implementation is not guaranteed to be the same
  36. * between two function calls. During early stages of the process you
  37. * might in fact get a noop implementation when Nextcloud isn't ready
  38. * to log. Therefore you MUST NOT cache the result of this function but
  39. * fetch a new logger for every log line you want to write.
  40. *
  41. * @param string|null $appId optional parameter to acquire the app-specific logger
  42. *
  43. * @return LoggerInterface
  44. * @since 24.0.0
  45. */
  46. function logger(string $appId = null): LoggerInterface {
  47. /** @psalm-suppress TypeDoesNotContainNull false-positive, it may contain null if we are logging from initialization */
  48. if (!class_exists(OC::class) || OC::$server === null) {
  49. // If someone calls this log before Nextcloud is initialized, there is
  50. // no logging available. In that case we return a noop implementation
  51. // TODO: evaluate whether logging to error_log could be an alternative
  52. return new NullLogger();
  53. }
  54. if ($appId !== null) {
  55. try {
  56. $appContainer = OC::$server->getRegisteredAppContainer($appId);
  57. return $appContainer->get(LoggerInterface::class);
  58. } catch (QueryException $e) {
  59. // Ignore and return the server logger below
  60. }
  61. }
  62. try {
  63. return OC::$server->get(LoggerInterface::class);
  64. } catch (QueryException $e) {
  65. return new NullLogger();
  66. }
  67. }