SlackHandler.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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\Logger;
  12. use Monolog\Formatter\LineFormatter;
  13. /**
  14. * Sends notifications through Slack API
  15. *
  16. * @author Greg Kedzierski <greg@gregkedzierski.com>
  17. * @see https://api.slack.com/
  18. */
  19. class SlackHandler extends SocketHandler
  20. {
  21. /**
  22. * Slack API token
  23. * @var string
  24. */
  25. private $token;
  26. /**
  27. * Slack channel (encoded ID or name)
  28. * @var string
  29. */
  30. private $channel;
  31. /**
  32. * Name of a bot
  33. * @var string
  34. */
  35. private $username;
  36. /**
  37. * Emoji icon name
  38. * @var string
  39. */
  40. private $iconEmoji;
  41. /**
  42. * Whether the message should be added to Slack as attachment (plain text otherwise)
  43. * @var bool
  44. */
  45. private $useAttachment;
  46. /**
  47. * Whether the the context/extra messages added to Slack as attachments are in a short style
  48. * @var bool
  49. */
  50. private $useShortAttachment;
  51. /**
  52. * Whether the attachment should include context and extra data
  53. * @var bool
  54. */
  55. private $includeContextAndExtra;
  56. /**
  57. * @var LineFormatter
  58. */
  59. private $lineFormatter;
  60. /**
  61. * @param string $token Slack API token
  62. * @param string $channel Slack channel (encoded ID or name)
  63. * @param string $username Name of a bot
  64. * @param bool $useAttachment Whether the message should be added to Slack as attachment (plain text otherwise)
  65. * @param string|null $iconEmoji The emoji name to use (or null)
  66. * @param int $level The minimum logging level at which this handler will be triggered
  67. * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
  68. * @param bool $useShortAttachment Whether the the context/extra messages added to Slack as attachments are in a short style
  69. * @param bool $includeContextAndExtra Whether the attachment should include context and extra data
  70. * @param bool $printSimpleMessage Whether the attachment should include only the message without extradata
  71. * @throws MissingExtensionException If no OpenSSL PHP extension configured
  72. */
  73. public function __construct($token, $channel, $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $level = Logger::CRITICAL, $bubble = true, $useShortAttachment = false, $includeContextAndExtra = false, $printSimpleMessage = false)
  74. {
  75. if (!extension_loaded('openssl')) {
  76. throw new MissingExtensionException('The OpenSSL PHP extension is required to use the SlackHandler');
  77. }
  78. parent::__construct('ssl://slack.com:443', $level, $bubble);
  79. $this->token = $token;
  80. $this->channel = $channel;
  81. $this->username = $username;
  82. $this->iconEmoji = is_string($iconEmoji) ? trim($iconEmoji, ':') : null;
  83. $this->useAttachment = $useAttachment;
  84. $this->useShortAttachment = $useShortAttachment;
  85. $this->includeContextAndExtra = $includeContextAndExtra;
  86. if ($this->includeContextAndExtra && $this->useShortAttachment) {
  87. $this->lineFormatter = new LineFormatter;
  88. }
  89. }
  90. /**
  91. * {@inheritdoc}
  92. *
  93. * @param array $record
  94. * @return string
  95. */
  96. protected function generateDataStream($record)
  97. {
  98. $content = $this->buildContent($record);
  99. return $this->buildHeader($content) . $content;
  100. }
  101. /**
  102. * Builds the body of API call
  103. *
  104. * @param array $record
  105. * @return string
  106. */
  107. private function buildContent($record)
  108. {
  109. $dataArray = $this->prepareContentData($record);
  110. return http_build_query($dataArray);
  111. }
  112. /**
  113. * Prepares content data
  114. *
  115. * @param array $record
  116. * @return array
  117. */
  118. protected function prepareContentData($record)
  119. {
  120. $dataArray = [
  121. 'token' => $this->token,
  122. 'channel' => $this->channel,
  123. 'username' => $this->username,
  124. 'text' => '',
  125. 'attachments' => [],
  126. ];
  127. if ($this->formatter && !$printSimpleMessage) {
  128. $message = $this->formatter->format($record);
  129. } else {
  130. $message = $record['message'];
  131. }
  132. if ($this->useAttachment) {
  133. $attachment = [
  134. 'fallback' => $message,
  135. 'color' => $this->getAttachmentColor($record['level']),
  136. 'fields' => [],
  137. ];
  138. if ($this->useShortAttachment) {
  139. $attachment['title'] = $record['level_name'];
  140. $attachment['text'] = $message;
  141. } else {
  142. $attachment['title'] = 'Message';
  143. $attachment['text'] = $message;
  144. $attachment['fields'][] = [
  145. 'title' => 'Level',
  146. 'value' => $record['level_name'],
  147. 'short' => true,
  148. ];
  149. }
  150. if ($this->includeContextAndExtra) {
  151. if (!empty($record['extra'])) {
  152. if ($this->useShortAttachment) {
  153. $attachment['fields'][] = [
  154. 'title' => "Extra",
  155. 'value' => $this->stringify($record['extra']),
  156. 'short' => $this->useShortAttachment,
  157. ];
  158. } else {
  159. // Add all extra fields as individual fields in attachment
  160. foreach ($record['extra'] as $var => $val) {
  161. $attachment['fields'][] = [
  162. 'title' => $var,
  163. 'value' => $val,
  164. 'short' => $this->useShortAttachment,
  165. ];
  166. }
  167. }
  168. }
  169. if (!empty($record['context'])) {
  170. if ($this->useShortAttachment) {
  171. $attachment['fields'][] = [
  172. 'title' => "Context",
  173. 'value' => $this->stringify($record['context']),
  174. 'short' => $this->useShortAttachment,
  175. ];
  176. } else {
  177. // Add all context fields as individual fields in attachment
  178. foreach ($record['context'] as $var => $val) {
  179. $attachment['fields'][] = [
  180. 'title' => $var,
  181. 'value' => $val,
  182. 'short' => $this->useShortAttachment,
  183. ];
  184. }
  185. }
  186. }
  187. }
  188. $dataArray['attachments'] = json_encode([$attachment]);
  189. } else {
  190. $dataArray['text'] = $message;
  191. }
  192. if ($this->iconEmoji) {
  193. $dataArray['icon_emoji'] = ":{$this->iconEmoji}:";
  194. }
  195. return $dataArray;
  196. }
  197. /**
  198. * Builds the header of the API Call
  199. *
  200. * @param string $content
  201. * @return string
  202. */
  203. private function buildHeader($content)
  204. {
  205. $header = "POST /api/chat.postMessage HTTP/1.1\r\n";
  206. $header .= "Host: slack.com\r\n";
  207. $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
  208. $header .= "Content-Length: " . strlen($content) . "\r\n";
  209. $header .= "\r\n";
  210. return $header;
  211. }
  212. /**
  213. * {@inheritdoc}
  214. *
  215. * @param array $record
  216. */
  217. protected function write(array $record)
  218. {
  219. parent::write($record);
  220. $res = $this->getResource();
  221. if (is_resource($res)) {
  222. @fread($res, 2048);
  223. }
  224. $this->closeSocket();
  225. }
  226. /**
  227. * Returned a Slack message attachment color associated with
  228. * provided level.
  229. *
  230. * @param int $level
  231. * @return string
  232. */
  233. protected function getAttachmentColor($level)
  234. {
  235. switch (true) {
  236. case $level >= Logger::ERROR:
  237. return 'danger';
  238. case $level >= Logger::WARNING:
  239. return 'warning';
  240. case $level >= Logger::INFO:
  241. return 'good';
  242. default:
  243. return '#e3e4e6';
  244. }
  245. }
  246. /**
  247. * Stringifies an array of key/value pairs to be used in attachment fields
  248. *
  249. * @param array $fields
  250. * @return string
  251. */
  252. protected function stringify($fields)
  253. {
  254. $string = '';
  255. foreach ($fields as $var => $val) {
  256. $string .= $var.': '.$this->lineFormatter->stringify($val)." | ";
  257. }
  258. $string = rtrim($string, " |");
  259. return $string;
  260. }
  261. }