SyslogTarget.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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()](https://secure.php.net/openlog).
  28. * Defaults to `null` which means to use the default options `LOG_ODELAY | LOG_PID`.
  29. * @see https://secure.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. * Starting from version 2.0.14, this method throws LogRuntimeException in case the log can not be exported.
  58. * @throws LogRuntimeException
  59. */
  60. public function export()
  61. {
  62. openlog($this->identity, $this->options, $this->facility);
  63. foreach ($this->messages as $message) {
  64. if (syslog($this->_syslogLevels[$message[1]], $this->formatMessage($message)) === false) {
  65. throw new LogRuntimeException('Unable to export log through system log!');
  66. }
  67. }
  68. closelog();
  69. }
  70. /**
  71. * {@inheritdoc}
  72. */
  73. public function formatMessage($message)
  74. {
  75. list($text, $level, $category, $timestamp) = $message;
  76. $level = Logger::getLevelName($level);
  77. if (!is_string($text)) {
  78. // exceptions may not be serializable if in the call stack somewhere is a Closure
  79. if ($text instanceof \Throwable || $text instanceof \Exception) {
  80. $text = (string) $text;
  81. } else {
  82. $text = VarDumper::export($text);
  83. }
  84. }
  85. $prefix = $this->getMessagePrefix($message);
  86. return "{$prefix}[$level][$category] $text";
  87. }
  88. }