SlackHandler.php 6.5 KB

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