1
0

Systemdlog.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OC\Log;
  7. use OC\SystemConfig;
  8. use OCP\HintException;
  9. use OCP\ILogger;
  10. use OCP\Log\IWriter;
  11. // The following fields are understood by systemd/journald, see
  12. // man systemd.journal-fields. All are optional:
  13. // MESSAGE=
  14. // The human-readable message string for this entry.
  15. // MESSAGE_ID=
  16. // A 128-bit message identifier ID
  17. // PRIORITY=
  18. // A priority value between 0 ("emerg") and 7 ("debug")
  19. // CODE_FILE=, CODE_LINE=, CODE_FUNC=
  20. // The code location generating this message, if known
  21. // ERRNO=
  22. // The low-level Unix error number causing this entry, if any.
  23. // SYSLOG_FACILITY=, SYSLOG_IDENTIFIER=, SYSLOG_PID=
  24. // Syslog compatibility fields
  25. class Systemdlog extends LogDetails implements IWriter {
  26. protected array $levels = [
  27. ILogger::DEBUG => 7,
  28. ILogger::INFO => 6,
  29. ILogger::WARN => 4,
  30. ILogger::ERROR => 3,
  31. ILogger::FATAL => 2,
  32. ];
  33. protected string $syslogId;
  34. public function __construct(
  35. SystemConfig $config,
  36. ?string $tag = null,
  37. ) {
  38. parent::__construct($config);
  39. if (!function_exists('sd_journal_send')) {
  40. throw new HintException(
  41. 'PHP extension php-systemd is not available.',
  42. 'Please install and enable PHP extension systemd if you wish to log to the Systemd journal.');
  43. }
  44. if ($tag === null) {
  45. $tag = $config->getValue('syslog_tag', 'Nextcloud');
  46. }
  47. $this->syslogId = $tag;
  48. }
  49. /**
  50. * Write a message to the log.
  51. * @param string|array $message
  52. */
  53. public function write(string $app, $message, int $level): void {
  54. $journal_level = $this->levels[$level];
  55. sd_journal_send('PRIORITY=' . $journal_level,
  56. 'SYSLOG_IDENTIFIER=' . $this->syslogId,
  57. 'MESSAGE=' . $this->logDetailsAsJSON($app, $message, $level));
  58. }
  59. }