SyslogTarget.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /**
  3. * @link https://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license https://www.yiiframework.com/license/
  6. */
  7. namespace yii\log;
  8. use yii\helpers\VarDumper;
  9. /**
  10. * SyslogTarget writes log to syslog.
  11. *
  12. * @author miramir <gmiramir@gmail.com>
  13. * @since 2.0
  14. */
  15. class SyslogTarget extends Target
  16. {
  17. /**
  18. * @var string syslog identity
  19. */
  20. public $identity;
  21. /**
  22. * @var int syslog facility.
  23. */
  24. public $facility = LOG_USER;
  25. /**
  26. * @var int|null openlog options. This is a bitfield passed as the `$option` parameter to [openlog()](https://www.php.net/openlog).
  27. * Defaults to `null` which means to use the default options `LOG_ODELAY | LOG_PID`.
  28. * @see https://www.php.net/openlog for available options.
  29. * @since 2.0.11
  30. */
  31. public $options;
  32. /**
  33. * @var array syslog levels
  34. */
  35. private $_syslogLevels = [
  36. Logger::LEVEL_TRACE => LOG_DEBUG,
  37. Logger::LEVEL_PROFILE_BEGIN => LOG_DEBUG,
  38. Logger::LEVEL_PROFILE_END => LOG_DEBUG,
  39. Logger::LEVEL_PROFILE => LOG_DEBUG,
  40. Logger::LEVEL_INFO => LOG_INFO,
  41. Logger::LEVEL_WARNING => LOG_WARNING,
  42. Logger::LEVEL_ERROR => LOG_ERR,
  43. ];
  44. /**
  45. * {@inheritdoc}
  46. */
  47. public function init()
  48. {
  49. parent::init();
  50. if ($this->options === null) {
  51. $this->options = LOG_ODELAY | LOG_PID;
  52. }
  53. }
  54. /**
  55. * Writes log messages to syslog.
  56. * Starting from version 2.0.14, this method throws LogRuntimeException in case the log can not be exported.
  57. * @throws LogRuntimeException
  58. */
  59. public function export()
  60. {
  61. openlog($this->identity, $this->options, $this->facility);
  62. foreach ($this->messages as $message) {
  63. if (syslog($this->_syslogLevels[$message[1]], $this->formatMessage($message)) === false) {
  64. throw new LogRuntimeException('Unable to export log through system log!');
  65. }
  66. }
  67. closelog();
  68. }
  69. /**
  70. * {@inheritdoc}
  71. */
  72. public function formatMessage($message)
  73. {
  74. list($text, $level, $category, $timestamp) = $message;
  75. $level = Logger::getLevelName($level);
  76. if (!is_string($text)) {
  77. // exceptions may not be serializable if in the call stack somewhere is a Closure
  78. if ($text instanceof \Exception || $text instanceof \Throwable) {
  79. $text = (string) $text;
  80. } else {
  81. $text = VarDumper::export($text);
  82. }
  83. }
  84. $prefix = $this->getMessagePrefix($message);
  85. return "{$prefix}[$level][$category] $text";
  86. }
  87. }