FlowdockFormatter.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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\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. public function __construct(string $source, string $sourceEmail)
  27. {
  28. $this->source = $source;
  29. $this->sourceEmail = $sourceEmail;
  30. }
  31. /**
  32. * {@inheritdoc}
  33. */
  34. public function format(array $record): array
  35. {
  36. $tags = [
  37. '#logs',
  38. '#' . strtolower($record['level_name']),
  39. '#' . $record['channel'],
  40. ];
  41. foreach ($record['extra'] as $value) {
  42. $tags[] = '#' . $value;
  43. }
  44. $subject = sprintf(
  45. 'in %s: %s - %s',
  46. $this->source,
  47. $record['level_name'],
  48. $this->getShortMessage($record['message'])
  49. );
  50. $record['flowdock'] = [
  51. 'source' => $this->source,
  52. 'from_address' => $this->sourceEmail,
  53. 'subject' => $subject,
  54. 'content' => $record['message'],
  55. 'tags' => $tags,
  56. 'project' => $this->source,
  57. ];
  58. return $record;
  59. }
  60. /**
  61. * {@inheritdoc}
  62. */
  63. public function formatBatch(array $records): array
  64. {
  65. $formatted = [];
  66. foreach ($records as $record) {
  67. $formatted[] = $this->format($record);
  68. }
  69. return $formatted;
  70. }
  71. public function getShortMessage(string $message): string
  72. {
  73. static $hasMbString;
  74. if (null === $hasMbString) {
  75. $hasMbString = function_exists('mb_strlen');
  76. }
  77. $maxLength = 45;
  78. if ($hasMbString) {
  79. if (mb_strlen($message, 'UTF-8') > $maxLength) {
  80. $message = mb_substr($message, 0, $maxLength - 4, 'UTF-8') . ' ...';
  81. }
  82. } else {
  83. if (strlen($message) > $maxLength) {
  84. $message = substr($message, 0, $maxLength - 4) . ' ...';
  85. }
  86. }
  87. return $message;
  88. }
  89. }