SlackbotHandler.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 Slack's Slackbot
  14. *
  15. * @author Haralan Dobrev <hkdobrev@gmail.com>
  16. * @see https://slack.com/apps/A0F81R8ET-slackbot
  17. */
  18. class SlackbotHandler extends AbstractProcessingHandler
  19. {
  20. /**
  21. * The slug of the Slack team
  22. * @var string
  23. */
  24. private $slackTeam;
  25. /**
  26. * Slackbot token
  27. * @var string
  28. */
  29. private $token;
  30. /**
  31. * Slack channel name
  32. * @var string
  33. */
  34. private $channel;
  35. /**
  36. * @param string $slackTeam Slack team slug
  37. * @param string $token Slackbot token
  38. * @param string $channel Slack channel (encoded ID or name)
  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. */
  42. public function __construct($slackTeam, $token, $channel, $level = Logger::CRITICAL, bool $bubble = true)
  43. {
  44. parent::__construct($level, $bubble);
  45. $this->slackTeam = $slackTeam;
  46. $this->token = $token;
  47. $this->channel = $channel;
  48. }
  49. /**
  50. * {@inheritdoc}
  51. *
  52. * @param array $record
  53. */
  54. protected function write(array $record): void
  55. {
  56. $slackbotUrl = sprintf(
  57. 'https://%s.slack.com/services/hooks/slackbot?token=%s&channel=%s',
  58. $this->slackTeam,
  59. $this->token,
  60. $this->channel
  61. );
  62. $ch = curl_init();
  63. curl_setopt($ch, CURLOPT_URL, $slackbotUrl);
  64. curl_setopt($ch, CURLOPT_POST, true);
  65. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  66. curl_setopt($ch, CURLOPT_POSTFIELDS, $record['message']);
  67. Curl\Util::execute($ch);
  68. }
  69. }