LogglyHandler.php 2.6 KB

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