Systemdlog.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2018, Johannes Ernst
  4. *
  5. * @author Johannes Ernst <jernst@indiecomputing.com>
  6. *
  7. * @license GNU AGPL version 3 or any later version
  8. *
  9. * This code is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU Affero General Public License, version 3,
  11. * as published by the Free Software Foundation.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU Affero General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public License, version 3,
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>
  20. *
  21. */
  22. namespace OC\Log;
  23. use OC\HintException;
  24. use OCP\ILogger;
  25. use OCP\IConfig;
  26. use OCP\Log\IWriter;
  27. // The following fields are understood by systemd/journald, see
  28. // man systemd.journal-fields. All are optional:
  29. // MESSAGE=
  30. // The human-readable message string for this entry.
  31. // MESSAGE_ID=
  32. // A 128-bit message identifier ID
  33. // PRIORITY=
  34. // A priority value between 0 ("emerg") and 7 ("debug")
  35. // CODE_FILE=, CODE_LINE=, CODE_FUNC=
  36. // The code location generating this message, if known
  37. // ERRNO=
  38. // The low-level Unix error number causing this entry, if any.
  39. // SYSLOG_FACILITY=, SYSLOG_IDENTIFIER=, SYSLOG_PID=
  40. // Syslog compatibility fields
  41. class Systemdlog implements IWriter {
  42. protected $levels = [
  43. ILogger::DEBUG => 7,
  44. ILogger::INFO => 6,
  45. ILogger::WARN => 4,
  46. ILogger::ERROR => 3,
  47. ILogger::FATAL => 2,
  48. ];
  49. protected $syslogId;
  50. public function __construct(IConfig $config) {
  51. if(!function_exists('sd_journal_send')) {
  52. throw new HintException(
  53. 'PHP extension php-systemd is not available.',
  54. 'Please install and enable PHP extension systemd if you wish to log to the Systemd journal.');
  55. }
  56. $this->syslogId = $config->getSystemValue('syslog_tag', 'Nextcloud');
  57. }
  58. /**
  59. * Write a message to the log.
  60. * @param string $app
  61. * @param string $message
  62. * @param int $level
  63. */
  64. public function write(string $app, $message, int $level) {
  65. $journal_level = $this->levels[$level];
  66. sd_journal_send('PRIORITY='.$journal_level,
  67. 'SYSLOG_IDENTIFIER='.$this->syslogId,
  68. 'MESSAGE={'.$app.'} '.$message);
  69. }
  70. }