LogglyHandler.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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\FormatterInterface;
  13. use Monolog\Formatter\LogglyFormatter;
  14. /**
  15. * Sends errors to Loggly.
  16. *
  17. * @author Przemek Sobstel <przemek@sobstel.org>
  18. * @author Adam Pancutt <adam@pancutt.com>
  19. * @author Gregory Barchard <gregory@barchard.net>
  20. */
  21. class LogglyHandler extends AbstractProcessingHandler
  22. {
  23. const HOST = 'logs-01.loggly.com';
  24. const ENDPOINT_SINGLE = 'inputs';
  25. const ENDPOINT_BATCH = 'bulk';
  26. protected $token;
  27. protected $tag = [];
  28. public function __construct($token, $level = Logger::DEBUG, $bubble = true)
  29. {
  30. if (!extension_loaded('curl')) {
  31. throw new \LogicException('The curl extension is needed to use the LogglyHandler');
  32. }
  33. $this->token = $token;
  34. parent::__construct($level, $bubble);
  35. }
  36. public function setTag($tag)
  37. {
  38. $tag = !empty($tag) ? $tag : [];
  39. $this->tag = is_array($tag) ? $tag : [$tag];
  40. }
  41. public function addTag($tag)
  42. {
  43. if (!empty($tag)) {
  44. $tag = is_array($tag) ? $tag : [$tag];
  45. $this->tag = array_unique(array_merge($this->tag, $tag));
  46. }
  47. }
  48. protected function write(array $record)
  49. {
  50. $this->send($record["formatted"], self::ENDPOINT_SINGLE);
  51. }
  52. public function handleBatch(array $records)
  53. {
  54. $level = $this->level;
  55. $records = array_filter($records, function ($record) use ($level) {
  56. return ($record['level'] >= $level);
  57. });
  58. if ($records) {
  59. $this->send($this->getFormatter()->formatBatch($records), self::ENDPOINT_BATCH);
  60. }
  61. }
  62. protected function send($data, $endpoint)
  63. {
  64. $url = sprintf("https://%s/%s/%s/", self::HOST, $endpoint, $this->token);
  65. $headers = ['Content-Type: application/json'];
  66. if (!empty($this->tag)) {
  67. $headers[] = 'X-LOGGLY-TAG: '.implode(',', $this->tag);
  68. }
  69. $ch = curl_init();
  70. curl_setopt($ch, CURLOPT_URL, $url);
  71. curl_setopt($ch, CURLOPT_POST, true);
  72. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  73. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  74. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  75. Curl\Util::execute($ch);
  76. }
  77. protected function getDefaultFormatter(): FormatterInterface
  78. {
  79. return new LogglyFormatter();
  80. }
  81. }