SyslogUdpHandler.php 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Handler;
  11. use DateTimeInterface;
  12. use Monolog\Handler\SyslogUdp\UdpSocket;
  13. use Monolog\Level;
  14. use Monolog\LogRecord;
  15. use Monolog\Utils;
  16. /**
  17. * A Handler for logging to a remote syslogd server.
  18. *
  19. * @author Jesper Skovgaard Nielsen <nulpunkt@gmail.com>
  20. * @author Dominik Kukacka <dominik.kukacka@gmail.com>
  21. */
  22. class SyslogUdpHandler extends AbstractSyslogHandler
  23. {
  24. const RFC3164 = 0;
  25. const RFC5424 = 1;
  26. const RFC5424e = 2;
  27. /** @var array<self::RFC*, string> */
  28. private array $dateFormats = [
  29. self::RFC3164 => 'M d H:i:s',
  30. self::RFC5424 => \DateTime::RFC3339,
  31. self::RFC5424e => \DateTime::RFC3339_EXTENDED,
  32. ];
  33. protected UdpSocket $socket;
  34. protected string $ident;
  35. /** @var self::RFC* */
  36. protected int $rfc;
  37. /**
  38. * @param string $host Either IP/hostname or a path to a unix socket (port must be 0 then)
  39. * @param int $port Port number, or 0 if $host is a unix socket
  40. * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant
  41. * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
  42. * @param string $ident Program name or tag for each log message.
  43. * @param int $rfc RFC to format the message for.
  44. * @throws MissingExtensionException when there is no socket extension
  45. *
  46. * @phpstan-param self::RFC* $rfc
  47. */
  48. public function __construct(string $host, int $port = 514, string|int $facility = LOG_USER, int|string|Level $level = Level::Debug, bool $bubble = true, string $ident = 'php', int $rfc = self::RFC5424)
  49. {
  50. if (!\extension_loaded('sockets')) {
  51. throw new MissingExtensionException('The sockets extension is required to use the SyslogUdpHandler');
  52. }
  53. parent::__construct($facility, $level, $bubble);
  54. $this->ident = $ident;
  55. $this->rfc = $rfc;
  56. $this->socket = new UdpSocket($host, $port);
  57. }
  58. protected function write(LogRecord $record): void
  59. {
  60. $lines = $this->splitMessageIntoLines($record->formatted);
  61. $header = $this->makeCommonSyslogHeader($this->toSyslogPriority($record->level), $record->datetime);
  62. foreach ($lines as $line) {
  63. $this->socket->write($line, $header);
  64. }
  65. }
  66. public function close(): void
  67. {
  68. $this->socket->close();
  69. }
  70. /**
  71. * @param string|string[] $message
  72. * @return string[]
  73. */
  74. private function splitMessageIntoLines($message): array
  75. {
  76. if (\is_array($message)) {
  77. $message = implode("\n", $message);
  78. }
  79. $lines = preg_split('/$\R?^/m', (string) $message, -1, PREG_SPLIT_NO_EMPTY);
  80. if (false === $lines) {
  81. $pcreErrorCode = preg_last_error();
  82. throw new \RuntimeException('Could not preg_split: ' . $pcreErrorCode . ' / ' . preg_last_error_msg());
  83. }
  84. return $lines;
  85. }
  86. /**
  87. * Make common syslog header (see rfc5424 or rfc3164)
  88. */
  89. protected function makeCommonSyslogHeader(int $severity, DateTimeInterface $datetime): string
  90. {
  91. $priority = $severity + $this->facility;
  92. $pid = getmypid();
  93. if (false === $pid) {
  94. $pid = '-';
  95. }
  96. $hostname = gethostname();
  97. if (false === $hostname) {
  98. $hostname = '-';
  99. }
  100. if ($this->rfc === self::RFC3164) {
  101. // see https://github.com/phpstan/phpstan/issues/5348
  102. // @phpstan-ignore-next-line
  103. $dateNew = $datetime->setTimezone(new \DateTimeZone('UTC'));
  104. $date = $dateNew->format($this->dateFormats[$this->rfc]);
  105. return "<$priority>" .
  106. $date . " " .
  107. $hostname . " " .
  108. $this->ident . "[" . $pid . "]: ";
  109. }
  110. $date = $datetime->format($this->dateFormats[$this->rfc]);
  111. return "<$priority>1 " .
  112. $date . " " .
  113. $hostname . " " .
  114. $this->ident . " " .
  115. $pid . " - - ";
  116. }
  117. /**
  118. * Inject your own socket, mainly used for testing
  119. *
  120. * @return $this
  121. */
  122. public function setSocket(UdpSocket $socket): self
  123. {
  124. $this->socket = $socket;
  125. return $this;
  126. }
  127. }