SyslogTarget.php 2.4 KB

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