SyslogUdpHandler.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  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 Monolog\Logger;
  12. use Monolog\Handler\SyslogUdp\UdpSocket;
  13. /**
  14. * A Handler for logging to a remote syslogd server.
  15. *
  16. * @author Jesper Skovgaard Nielsen <nulpunkt@gmail.com>
  17. */
  18. class SyslogUdpHandler extends AbstractSyslogHandler
  19. {
  20. protected $socket;
  21. protected $ident;
  22. /**
  23. * @param string $host
  24. * @param int $port
  25. * @param mixed $facility
  26. * @param int $level The minimum logging level at which this handler will be triggered
  27. * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
  28. * @param string $ident Program name or tag for each log message.
  29. */
  30. public function __construct($host, $port = 514, $facility = LOG_USER, $level = Logger::DEBUG, $bubble = true, $ident = 'php')
  31. {
  32. parent::__construct($facility, $level, $bubble);
  33. $this->ident = $ident;
  34. $this->socket = new UdpSocket($host, $port ?: 514);
  35. }
  36. protected function write(array $record)
  37. {
  38. $lines = $this->splitMessageIntoLines($record['formatted']);
  39. $header = $this->makeCommonSyslogHeader($this->logLevels[$record['level']]);
  40. foreach ($lines as $line) {
  41. $this->socket->write($line, $header);
  42. }
  43. }
  44. public function close()
  45. {
  46. $this->socket->close();
  47. }
  48. private function splitMessageIntoLines($message)
  49. {
  50. if (is_array($message)) {
  51. $message = implode("\n", $message);
  52. }
  53. return preg_split('/$\R?^/m', $message, -1, PREG_SPLIT_NO_EMPTY);
  54. }
  55. /**
  56. * Make common syslog header (see rfc5424)
  57. */
  58. protected function makeCommonSyslogHeader($severity)
  59. {
  60. $priority = $severity + $this->facility;
  61. if (!$pid = getmypid()) {
  62. $pid = '-';
  63. }
  64. if (!$hostname = gethostname()) {
  65. $hostname = '-';
  66. }
  67. return "<$priority>1 " .
  68. $this->getDateTime() . " " .
  69. $hostname . " " .
  70. $this->ident . " " .
  71. $pid . " - - ";
  72. }
  73. protected function getDateTime()
  74. {
  75. return date(\DateTime::RFC3339);
  76. }
  77. /**
  78. * Inject your own socket, mainly used for testing
  79. */
  80. public function setSocket($socket)
  81. {
  82. $this->socket = $socket;
  83. }
  84. }