SlackHandler.php 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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\Formatter\FormatterInterface;
  12. use Monolog\Logger;
  13. use Monolog\Handler\Slack\SlackRecord;
  14. /**
  15. * Sends notifications through Slack API
  16. *
  17. * @author Greg Kedzierski <greg@gregkedzierski.com>
  18. * @see https://api.slack.com/
  19. */
  20. class SlackHandler extends SocketHandler
  21. {
  22. /**
  23. * Slack API token
  24. * @var string
  25. */
  26. private $token;
  27. /**
  28. * Instance of the SlackRecord util class preparing data for Slack API.
  29. * @var SlackRecord
  30. */
  31. private $slackRecord;
  32. /**
  33. * @param string $token Slack API token
  34. * @param string $channel Slack channel (encoded ID or name)
  35. * @param string|null $username Name of a bot
  36. * @param bool $useAttachment Whether the message should be added to Slack as attachment (plain text otherwise)
  37. * @param string|null $iconEmoji The emoji name to use (or null)
  38. * @param int $level The minimum logging level at which this handler will be triggered
  39. * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
  40. * @param bool $useShortAttachment Whether the the context/extra messages added to Slack as attachments are in a short style
  41. * @param bool $includeContextAndExtra Whether the attachment should include context and extra data
  42. * @param array $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2']
  43. * @throws MissingExtensionException If no OpenSSL PHP extension configured
  44. */
  45. public function __construct(
  46. string $token,
  47. string $channel,
  48. ?string $username = null,
  49. bool $useAttachment = true,
  50. ?string $iconEmoji = null,
  51. $level = Logger::CRITICAL,
  52. bool $bubble = true,
  53. bool $useShortAttachment = false,
  54. bool $includeContextAndExtra = false,
  55. array $excludeFields = array()
  56. ) {
  57. if (!extension_loaded('openssl')) {
  58. throw new MissingExtensionException('The OpenSSL PHP extension is required to use the SlackHandler');
  59. }
  60. parent::__construct('ssl://slack.com:443', $level, $bubble);
  61. $this->slackRecord = new SlackRecord(
  62. $channel,
  63. $username,
  64. $useAttachment,
  65. $iconEmoji,
  66. $useShortAttachment,
  67. $includeContextAndExtra,
  68. $excludeFields
  69. );
  70. $this->token = $token;
  71. }
  72. public function getSlackRecord(): SlackRecord
  73. {
  74. return $this->slackRecord;
  75. }
  76. public function getToken(): string
  77. {
  78. return $this->token;
  79. }
  80. /**
  81. * {@inheritdoc}
  82. */
  83. protected function generateDataStream(array $record): string
  84. {
  85. $content = $this->buildContent($record);
  86. return $this->buildHeader($content) . $content;
  87. }
  88. /**
  89. * Builds the body of API call
  90. */
  91. private function buildContent(array $record): string
  92. {
  93. $dataArray = $this->prepareContentData($record);
  94. return http_build_query($dataArray);
  95. }
  96. protected function prepareContentData(array $record): array
  97. {
  98. $dataArray = $this->slackRecord->getSlackData($record);
  99. $dataArray['token'] = $this->token;
  100. if (!empty($dataArray['attachments'])) {
  101. $dataArray['attachments'] = json_encode($dataArray['attachments']);
  102. }
  103. return $dataArray;
  104. }
  105. /**
  106. * Builds the header of the API Call
  107. */
  108. private function buildHeader(string $content): string
  109. {
  110. $header = "POST /api/chat.postMessage HTTP/1.1\r\n";
  111. $header .= "Host: slack.com\r\n";
  112. $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
  113. $header .= "Content-Length: " . strlen($content) . "\r\n";
  114. $header .= "\r\n";
  115. return $header;
  116. }
  117. /**
  118. * {@inheritdoc}
  119. */
  120. protected function write(array $record): void
  121. {
  122. parent::write($record);
  123. $this->finalizeWrite();
  124. }
  125. /**
  126. * Finalizes the request by reading some bytes and then closing the socket
  127. *
  128. * If we do not read some but close the socket too early, slack sometimes
  129. * drops the request entirely.
  130. */
  131. protected function finalizeWrite(): void
  132. {
  133. $res = $this->getResource();
  134. if (is_resource($res)) {
  135. @fread($res, 2048);
  136. }
  137. $this->closeSocket();
  138. }
  139. public function setFormatter(FormatterInterface $formatter): HandlerInterface
  140. {
  141. parent::setFormatter($formatter);
  142. $this->slackRecord->setFormatter($formatter);
  143. return $this;
  144. }
  145. public function getFormatter(): FormatterInterface
  146. {
  147. $formatter = parent::getFormatter();
  148. $this->slackRecord->setFormatter($formatter);
  149. return $formatter;
  150. }
  151. }