SyslogHandler.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 Monolog\Logger;
  12. /**
  13. * Logs to syslog service.
  14. *
  15. * usage example:
  16. *
  17. * $log = new Logger('application');
  18. * $syslog = new SyslogHandler('myfacility', 'local6');
  19. * $formatter = new LineFormatter("%channel%.%level_name%: %message% %extra%");
  20. * $syslog->setFormatter($formatter);
  21. * $log->pushHandler($syslog);
  22. *
  23. * @author Sven Paulus <sven@karlsruhe.org>
  24. */
  25. class SyslogHandler extends AbstractSyslogHandler
  26. {
  27. protected $ident;
  28. protected $logopts;
  29. /**
  30. * @param string $ident
  31. * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant
  32. * @param string|int $level The minimum logging level at which this handler will be triggered
  33. * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
  34. * @param int $logopts Option flags for the openlog() call, defaults to LOG_PID
  35. */
  36. public function __construct(string $ident, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, int $logopts = LOG_PID)
  37. {
  38. parent::__construct($facility, $level, $bubble);
  39. $this->ident = $ident;
  40. $this->logopts = $logopts;
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. public function close(): void
  46. {
  47. closelog();
  48. }
  49. /**
  50. * {@inheritdoc}
  51. */
  52. protected function write(array $record): void
  53. {
  54. if (!openlog($this->ident, $this->logopts, $this->facility)) {
  55. throw new \LogicException('Can\'t open syslog for ident "'.$this->ident.'" and facility "'.$this->facility.'"');
  56. }
  57. syslog($this->logLevels[$record['level']], (string) $record['formatted']);
  58. }
  59. }