ChromePHPFormatter.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. use Monolog\Level;
  12. use Monolog\LogRecord;
  13. /**
  14. * Formats a log message according to the ChromePHP array format
  15. *
  16. * @author Christophe Coevoet <stof@notk.org>
  17. */
  18. class ChromePHPFormatter implements FormatterInterface
  19. {
  20. /**
  21. * Translates Monolog log levels to Wildfire levels.
  22. *
  23. * @return 'log'|'info'|'warn'|'error'
  24. */
  25. private function toWildfireLevel(Level $level): string
  26. {
  27. return match ($level) {
  28. Level::Debug => 'log',
  29. Level::Info => 'info',
  30. Level::Notice => 'info',
  31. Level::Warning => 'warn',
  32. Level::Error => 'error',
  33. Level::Critical => 'error',
  34. Level::Alert => 'error',
  35. Level::Emergency => 'error',
  36. };
  37. }
  38. /**
  39. * @inheritDoc
  40. */
  41. public function format(LogRecord $record)
  42. {
  43. // Retrieve the line and file if set and remove them from the formatted extra
  44. $backtrace = 'unknown';
  45. if (isset($record->extra['file'], $record->extra['line'])) {
  46. $backtrace = $record->extra['file'].' : '.$record->extra['line'];
  47. unset($record->extra['file'], $record->extra['line']);
  48. }
  49. $message = ['message' => $record->message];
  50. if (\count($record->context) > 0) {
  51. $message['context'] = $record->context;
  52. }
  53. if (\count($record->extra) > 0) {
  54. $message['extra'] = $record->extra;
  55. }
  56. if (\count($message) === 1) {
  57. $message = reset($message);
  58. }
  59. return [
  60. $record->channel,
  61. $message,
  62. $backtrace,
  63. $this->toWildfireLevel($record->level),
  64. ];
  65. }
  66. /**
  67. * @inheritDoc
  68. */
  69. public function formatBatch(array $records)
  70. {
  71. $formatted = [];
  72. foreach ($records as $record) {
  73. $formatted[] = $this->format($record);
  74. }
  75. return $formatted;
  76. }
  77. }