HipChatHandler.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. /**
  13. * Sends notifications through the hipchat api to a hipchat room
  14. *
  15. * This handler only supports the API v2
  16. *
  17. * Notes:
  18. * API token - HipChat API token
  19. * Room - HipChat Room Id or name, where messages are sent
  20. * Name - Name used to send the message (from)
  21. * notify - Should the message trigger a notification in the clients
  22. *
  23. * @author Rafael Dohms <rafael@doh.ms>
  24. * @see https://www.hipchat.com/docs/api
  25. */
  26. class HipChatHandler extends SocketHandler
  27. {
  28. /**
  29. * The maximum allowed length for the message.
  30. */
  31. protected const MAXIMUM_MESSAGE_LENGTH = 9500;
  32. /**
  33. * @var string
  34. */
  35. private $token;
  36. /**
  37. * @var string
  38. */
  39. private $room;
  40. /**
  41. * @var string
  42. */
  43. private $name;
  44. /**
  45. * @var bool
  46. */
  47. private $notify;
  48. /**
  49. * @var string
  50. */
  51. private $format;
  52. /**
  53. * @var string
  54. */
  55. private $host;
  56. /**
  57. * @param string $token HipChat API Token
  58. * @param string $room The room that should be alerted of the message (Id or Name)
  59. * @param string|null $name Name used in the "from" field.
  60. * @param bool $notify Trigger a notification in clients or not
  61. * @param string|int $level The minimum logging level at which this handler will be triggered
  62. * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
  63. * @param bool $useSSL Whether to connect via SSL.
  64. * @param string $format The format of the messages (default to text, can be set to html if you have html in the messages)
  65. * @param string $host The HipChat server hostname.
  66. */
  67. public function __construct(
  68. string $token,
  69. string $room,
  70. ?string $name = 'Monolog',
  71. bool $notify = false,
  72. $level = Logger::CRITICAL,
  73. bool $bubble = true,
  74. bool $useSSL = true,
  75. string $format = 'text',
  76. string $host = 'api.hipchat.com'
  77. ) {
  78. $connectionString = $useSSL ? 'ssl://'.$host.':443' : $host.':80';
  79. parent::__construct($connectionString, $level, $bubble);
  80. $this->token = $token;
  81. $this->name = $name;
  82. $this->notify = $notify;
  83. $this->room = $room;
  84. $this->format = $format;
  85. $this->host = $host;
  86. }
  87. /**
  88. * {@inheritdoc}
  89. */
  90. protected function generateDataStream(array $record): string
  91. {
  92. $content = $this->buildContent($record);
  93. return $this->buildHeader($content) . $content;
  94. }
  95. /**
  96. * Builds the body of API call
  97. */
  98. private function buildContent(array $record): string
  99. {
  100. $dataArray = [
  101. 'notify' => $this->notify ? 'true' : 'false',
  102. 'message' => $record['formatted'],
  103. 'message_format' => $this->format,
  104. 'color' => $this->getAlertColor($record['level']),
  105. ];
  106. if (!$this->validateStringLength($dataArray['message'], static::MAXIMUM_MESSAGE_LENGTH)) {
  107. if (function_exists('mb_substr')) {
  108. $dataArray['message'] = mb_substr($dataArray['message'], 0, static::MAXIMUM_MESSAGE_LENGTH).' [truncated]';
  109. } else {
  110. $dataArray['message'] = substr($dataArray['message'], 0, static::MAXIMUM_MESSAGE_LENGTH).' [truncated]';
  111. }
  112. }
  113. // append the sender name if it is set
  114. // always append it if we use the v1 api (it is required in v1)
  115. if ($this->name !== null) {
  116. $dataArray['from'] = (string) $this->name;
  117. }
  118. return http_build_query($dataArray);
  119. }
  120. /**
  121. * Builds the header of the API Call
  122. */
  123. private function buildHeader(string $content): string
  124. {
  125. // needed for rooms with special (spaces, etc) characters in the name
  126. $room = rawurlencode($this->room);
  127. $header = "POST /v2/room/{$room}/notification?auth_token={$this->token} HTTP/1.1\r\n";
  128. $header .= "Host: {$this->host}\r\n";
  129. $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
  130. $header .= "Content-Length: " . strlen($content) . "\r\n";
  131. $header .= "\r\n";
  132. return $header;
  133. }
  134. /**
  135. * Assigns a color to each level of log records.
  136. */
  137. protected function getAlertColor(int $level): string
  138. {
  139. switch (true) {
  140. case $level >= Logger::ERROR:
  141. return 'red';
  142. case $level >= Logger::WARNING:
  143. return 'yellow';
  144. case $level >= Logger::INFO:
  145. return 'green';
  146. case $level == Logger::DEBUG:
  147. return 'gray';
  148. default:
  149. return 'yellow';
  150. }
  151. }
  152. /**
  153. * {@inheritdoc}
  154. */
  155. protected function write(array $record): void
  156. {
  157. parent::write($record);
  158. $this->finalizeWrite();
  159. }
  160. /**
  161. * Finalizes the request by reading some bytes and then closing the socket
  162. *
  163. * If we do not read some but close the socket too early, hipchat sometimes
  164. * drops the request entirely.
  165. */
  166. protected function finalizeWrite(): void
  167. {
  168. $res = $this->getResource();
  169. if (is_resource($res)) {
  170. @fread($res, 2048);
  171. }
  172. $this->closeSocket();
  173. }
  174. /**
  175. * {@inheritdoc}
  176. */
  177. public function handleBatch(array $records): void
  178. {
  179. if (count($records) == 0) {
  180. return;
  181. }
  182. $batchRecords = $this->combineRecords($records);
  183. foreach ($batchRecords as $batchRecord) {
  184. $this->handle($batchRecord);
  185. }
  186. }
  187. /**
  188. * Combines multiple records into one. Error level of the combined record
  189. * will be the highest level from the given records. Datetime will be taken
  190. * from the first record.
  191. */
  192. private function combineRecords(array $records): array
  193. {
  194. $batchRecord = null;
  195. $batchRecords = [];
  196. $messages = [];
  197. $formattedMessages = [];
  198. $level = 0;
  199. $levelName = null;
  200. $datetime = null;
  201. foreach ($records as $record) {
  202. $record = $this->processRecord($record);
  203. if ($record['level'] > $level) {
  204. $level = $record['level'];
  205. $levelName = $record['level_name'];
  206. }
  207. if (null === $datetime) {
  208. $datetime = $record['datetime'];
  209. }
  210. $messages[] = $record['message'];
  211. $messageStr = implode(PHP_EOL, $messages);
  212. $formattedMessages[] = $this->getFormatter()->format($record);
  213. $formattedMessageStr = implode('', $formattedMessages);
  214. $batchRecord = [
  215. 'message' => $messageStr,
  216. 'formatted' => $formattedMessageStr,
  217. 'context' => [],
  218. 'extra' => [],
  219. ];
  220. if (!$this->validateStringLength($batchRecord['formatted'], static::MAXIMUM_MESSAGE_LENGTH)) {
  221. // Pop the last message and implode the remaining messages
  222. $lastMessage = array_pop($messages);
  223. $lastFormattedMessage = array_pop($formattedMessages);
  224. $batchRecord['message'] = implode(PHP_EOL, $messages);
  225. $batchRecord['formatted'] = implode('', $formattedMessages);
  226. $batchRecords[] = $batchRecord;
  227. $messages = [$lastMessage];
  228. $formattedMessages = [$lastFormattedMessage];
  229. $batchRecord = null;
  230. }
  231. }
  232. if (null !== $batchRecord) {
  233. $batchRecords[] = $batchRecord;
  234. }
  235. // Set the max level and datetime for all records
  236. foreach ($batchRecords as &$batchRecord) {
  237. $batchRecord = array_merge(
  238. $batchRecord,
  239. [
  240. 'level' => $level,
  241. 'level_name' => $levelName,
  242. 'datetime' => $datetime,
  243. ]
  244. );
  245. }
  246. return $batchRecords;
  247. }
  248. /**
  249. * Validates the length of a string.
  250. *
  251. * If the `mb_strlen()` function is available, it will use that, as HipChat
  252. * allows UTF-8 characters. Otherwise, it will fall back to `strlen()`.
  253. *
  254. * Note that this might cause false failures in the specific case of using
  255. * a valid name with less than 16 characters, but 16 or more bytes, on a
  256. * system where `mb_strlen()` is unavailable.
  257. */
  258. private function validateStringLength(string $str, int $length): bool
  259. {
  260. if (function_exists('mb_strlen')) {
  261. return (mb_strlen($str) <= $length);
  262. }
  263. return (strlen($str) <= $length);
  264. }
  265. }