FlowdockFormatter.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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\Formatter;
  11. /**
  12. * formats the record to be used in the FlowdockHandler
  13. *
  14. * @author Dominik Liebler <liebler.dominik@gmail.com>
  15. */
  16. class FlowdockFormatter implements FormatterInterface
  17. {
  18. /**
  19. * @var string
  20. */
  21. private $source;
  22. /**
  23. * @var string
  24. */
  25. private $sourceEmail;
  26. /**
  27. * @param string $source
  28. * @param string $sourceEmail
  29. */
  30. public function __construct($source, $sourceEmail)
  31. {
  32. $this->source = $source;
  33. $this->sourceEmail = $sourceEmail;
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public function format(array $record)
  39. {
  40. $tags = array(
  41. '#logs',
  42. '#' . strtolower($record['level_name']),
  43. '#' . $record['channel'],
  44. );
  45. foreach ($record['extra'] as $value) {
  46. $tags[] = '#' . $value;
  47. }
  48. $subject = sprintf(
  49. 'in %s: %s - %s',
  50. $this->source,
  51. $record['level_name'],
  52. $this->getShortMessage($record['message'])
  53. );
  54. $record['flowdock'] = array(
  55. 'source' => $this->source,
  56. 'from_address' => $this->sourceEmail,
  57. 'subject' => $subject,
  58. 'content' => $record['message'],
  59. 'tags' => $tags,
  60. 'project' => $this->source,
  61. );
  62. return $record;
  63. }
  64. /**
  65. * {@inheritdoc}
  66. */
  67. public function formatBatch(array $records)
  68. {
  69. $formatted = array();
  70. foreach ($records as $record) {
  71. $formatted[] = $this->format($record);
  72. }
  73. return $formatted;
  74. }
  75. /**
  76. * @param string $message
  77. *
  78. * @return string
  79. */
  80. public function getShortMessage($message)
  81. {
  82. static $hasMbString;
  83. if (null === $hasMbString) {
  84. $hasMbString = function_exists('mb_strlen');
  85. }
  86. $maxLength = 45;
  87. if ($hasMbString) {
  88. if (mb_strlen($message, 'UTF-8') > $maxLength) {
  89. $message = mb_substr($message, 0, $maxLength - 4, 'UTF-8') . ' ...';
  90. }
  91. } else {
  92. if (strlen($message) > $maxLength) {
  93. $message = substr($message, 0, $maxLength - 4) . ' ...';
  94. }
  95. }
  96. return $message;
  97. }
  98. }