functions.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. if (!class_exists(OC::class) || OC::$server === null) {
  48. // If someone calls this log before Nextcloud is initialized, there is
  49. // no logging available. In that case we return a noop implementation
  50. // TODO: evaluate whether logging to error_log could be an alternative
  51. return new NullLogger();
  52. }
  53. if ($appId !== null) {
  54. try {
  55. $appContainer = OC::$server->getRegisteredAppContainer($appId);
  56. return $appContainer->get(LoggerInterface::class);
  57. } catch (QueryException $e) {
  58. // Ignore and return the server logger below
  59. }
  60. }
  61. try {
  62. return OC::$server->get(LoggerInterface::class);
  63. } catch (QueryException $e) {
  64. return new NullLogger();
  65. }
  66. }