| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296 |
- <?php declare(strict_types=1);
- /*
- * This file is part of the Monolog package.
- *
- * (c) Jordi Boggiano <j.boggiano@seld.be>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
- namespace Monolog\Handler;
- use Monolog\Logger;
- use Monolog\Formatter\LineFormatter;
- /**
- * Sends notifications through Slack API
- *
- * @author Greg Kedzierski <greg@gregkedzierski.com>
- * @see https://api.slack.com/
- */
- class SlackHandler extends SocketHandler
- {
- /**
- * Slack API token
- * @var string
- */
- private $token;
- /**
- * Slack channel (encoded ID or name)
- * @var string
- */
- private $channel;
- /**
- * Name of a bot
- * @var string
- */
- private $username;
- /**
- * Emoji icon name
- * @var string
- */
- private $iconEmoji;
- /**
- * Whether the message should be added to Slack as attachment (plain text otherwise)
- * @var bool
- */
- private $useAttachment;
- /**
- * Whether the the context/extra messages added to Slack as attachments are in a short style
- * @var bool
- */
- private $useShortAttachment;
- /**
- * Whether the attachment should include context and extra data
- * @var bool
- */
- private $includeContextAndExtra;
- /**
- * @var LineFormatter
- */
- private $lineFormatter;
- /**
- * @param string $token Slack API token
- * @param string $channel Slack channel (encoded ID or name)
- * @param string $username Name of a bot
- * @param bool $useAttachment Whether the message should be added to Slack as attachment (plain text otherwise)
- * @param string|null $iconEmoji The emoji name to use (or null)
- * @param int $level The minimum logging level at which this handler will be triggered
- * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
- * @param bool $useShortAttachment Whether the the context/extra messages added to Slack as attachments are in a short style
- * @param bool $includeContextAndExtra Whether the attachment should include context and extra data
- * @param bool $printSimpleMessage Whether the attachment should include only the message without extradata
- * @throws MissingExtensionException If no OpenSSL PHP extension configured
- */
- public function __construct($token, $channel, $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $level = Logger::CRITICAL, $bubble = true, $useShortAttachment = false, $includeContextAndExtra = false, $printSimpleMessage = false)
- {
- if (!extension_loaded('openssl')) {
- throw new MissingExtensionException('The OpenSSL PHP extension is required to use the SlackHandler');
- }
- parent::__construct('ssl://slack.com:443', $level, $bubble);
- $this->token = $token;
- $this->channel = $channel;
- $this->username = $username;
- $this->iconEmoji = is_string($iconEmoji) ? trim($iconEmoji, ':') : null;
- $this->useAttachment = $useAttachment;
- $this->useShortAttachment = $useShortAttachment;
- $this->includeContextAndExtra = $includeContextAndExtra;
- if ($this->includeContextAndExtra && $this->useShortAttachment) {
- $this->lineFormatter = new LineFormatter;
- }
- }
- /**
- * {@inheritdoc}
- *
- * @param array $record
- * @return string
- */
- protected function generateDataStream($record)
- {
- $content = $this->buildContent($record);
- return $this->buildHeader($content) . $content;
- }
- /**
- * Builds the body of API call
- *
- * @param array $record
- * @return string
- */
- private function buildContent($record)
- {
- $dataArray = $this->prepareContentData($record);
- return http_build_query($dataArray);
- }
- /**
- * Prepares content data
- *
- * @param array $record
- * @return array
- */
- protected function prepareContentData($record)
- {
- $dataArray = [
- 'token' => $this->token,
- 'channel' => $this->channel,
- 'username' => $this->username,
- 'text' => '',
- 'attachments' => [],
- ];
- if ($this->formatter && !$printSimpleMessage) {
- $message = $this->formatter->format($record);
- } else {
- $message = $record['message'];
- }
- if ($this->useAttachment) {
- $attachment = [
- 'fallback' => $message,
- 'color' => $this->getAttachmentColor($record['level']),
- 'fields' => [],
- ];
- if ($this->useShortAttachment) {
- $attachment['title'] = $record['level_name'];
- $attachment['text'] = $message;
- } else {
- $attachment['title'] = 'Message';
- $attachment['text'] = $message;
- $attachment['fields'][] = [
- 'title' => 'Level',
- 'value' => $record['level_name'],
- 'short' => true,
- ];
- }
- if ($this->includeContextAndExtra) {
- if (!empty($record['extra'])) {
- if ($this->useShortAttachment) {
- $attachment['fields'][] = [
- 'title' => "Extra",
- 'value' => $this->stringify($record['extra']),
- 'short' => $this->useShortAttachment,
- ];
- } else {
- // Add all extra fields as individual fields in attachment
- foreach ($record['extra'] as $var => $val) {
- $attachment['fields'][] = [
- 'title' => $var,
- 'value' => $val,
- 'short' => $this->useShortAttachment,
- ];
- }
- }
- }
- if (!empty($record['context'])) {
- if ($this->useShortAttachment) {
- $attachment['fields'][] = [
- 'title' => "Context",
- 'value' => $this->stringify($record['context']),
- 'short' => $this->useShortAttachment,
- ];
- } else {
- // Add all context fields as individual fields in attachment
- foreach ($record['context'] as $var => $val) {
- $attachment['fields'][] = [
- 'title' => $var,
- 'value' => $val,
- 'short' => $this->useShortAttachment,
- ];
- }
- }
- }
- }
- $dataArray['attachments'] = json_encode([$attachment]);
- } else {
- $dataArray['text'] = $message;
- }
- if ($this->iconEmoji) {
- $dataArray['icon_emoji'] = ":{$this->iconEmoji}:";
- }
- return $dataArray;
- }
- /**
- * Builds the header of the API Call
- *
- * @param string $content
- * @return string
- */
- private function buildHeader($content)
- {
- $header = "POST /api/chat.postMessage HTTP/1.1\r\n";
- $header .= "Host: slack.com\r\n";
- $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
- $header .= "Content-Length: " . strlen($content) . "\r\n";
- $header .= "\r\n";
- return $header;
- }
- /**
- * {@inheritdoc}
- *
- * @param array $record
- */
- protected function write(array $record)
- {
- parent::write($record);
- $res = $this->getResource();
- if (is_resource($res)) {
- @fread($res, 2048);
- }
- $this->closeSocket();
- }
- /**
- * Returned a Slack message attachment color associated with
- * provided level.
- *
- * @param int $level
- * @return string
- */
- protected function getAttachmentColor($level)
- {
- switch (true) {
- case $level >= Logger::ERROR:
- return 'danger';
- case $level >= Logger::WARNING:
- return 'warning';
- case $level >= Logger::INFO:
- return 'good';
- default:
- return '#e3e4e6';
- }
- }
- /**
- * Stringifies an array of key/value pairs to be used in attachment fields
- *
- * @param array $fields
- * @return string
- */
- protected function stringify($fields)
- {
- $string = '';
- foreach ($fields as $var => $val) {
- $string .= $var.': '.$this->lineFormatter->stringify($val)." | ";
- }
- $string = rtrim($string, " |");
- return $string;
- }
- }
|