IFTTTHandler.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  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. * IFTTTHandler uses cURL to trigger IFTTT Maker actions
  14. *
  15. * Register a secret key and trigger/event name at https://ifttt.com/maker
  16. *
  17. * value1 will be the channel from monolog's Logger constructor,
  18. * value2 will be the level name (ERROR, WARNING, ..)
  19. * value3 will be the log record's message
  20. *
  21. * @author Nehal Patel <nehal@nehalpatel.me>
  22. */
  23. class IFTTTHandler extends AbstractProcessingHandler
  24. {
  25. private $eventName;
  26. private $secretKey;
  27. /**
  28. * @param string $eventName The name of the IFTTT Maker event that should be triggered
  29. * @param string $secretKey A valid IFTTT secret key
  30. * @param int $level The minimum logging level at which this handler will be triggered
  31. * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
  32. */
  33. public function __construct($eventName, $secretKey, $level = Logger::ERROR, $bubble = true)
  34. {
  35. $this->eventName = $eventName;
  36. $this->secretKey = $secretKey;
  37. parent::__construct($level, $bubble);
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function write(array $record)
  43. {
  44. $postData = array(
  45. "value1" => $record["channel"],
  46. "value2" => $record["level_name"],
  47. "value3" => $record["message"],
  48. );
  49. $postString = json_encode($postData);
  50. $ch = curl_init();
  51. curl_setopt($ch, CURLOPT_URL, "https://maker.ifttt.com/trigger/" . $this->eventName . "/with/key/" . $this->secretKey);
  52. curl_setopt($ch, CURLOPT_POST, true);
  53. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  54. curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
  55. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  56. "Content-Type: application/json",
  57. ));
  58. Curl\Util::execute($ch);
  59. }
  60. }