SyslogUdpHandler.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. /**
  22. * @param string $host
  23. * @param int $port
  24. * @param mixed $facility
  25. * @param integer $level The minimum logging level at which this handler will be triggered
  26. * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
  27. */
  28. public function __construct($host, $port = 514, $facility = LOG_USER, $level = Logger::DEBUG, $bubble = true)
  29. {
  30. parent::__construct($facility, $level, $bubble);
  31. $this->socket = new UdpSocket($host, $port ?: 514);
  32. }
  33. protected function write(array $record)
  34. {
  35. $lines = $this->splitMessageIntoLines($record['formatted']);
  36. $header = $this->makeCommonSyslogHeader($this->logLevels[$record['level']]);
  37. foreach ($lines as $line) {
  38. $this->socket->write($line, $header);
  39. }
  40. }
  41. public function close()
  42. {
  43. $this->socket->close();
  44. }
  45. private function splitMessageIntoLines($message)
  46. {
  47. if (is_array($message)) {
  48. $message = implode("\n", $message);
  49. }
  50. return preg_split('/$\R?^/m', $message);
  51. }
  52. /**
  53. * Make common syslog header (see rfc5424)
  54. */
  55. protected function makeCommonSyslogHeader($severity)
  56. {
  57. $priority = $severity + $this->facility;
  58. return "<$priority>1 ";
  59. }
  60. /**
  61. * Inject your own socket, mainly used for testing
  62. */
  63. public function setSocket($socket)
  64. {
  65. $this->socket = $socket;
  66. }
  67. }