GitProcessor.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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\Processor;
  11. use Monolog\Logger;
  12. /**
  13. * Injects Git branch and Git commit SHA in all records
  14. *
  15. * @author Nick Otter
  16. * @author Jordi Boggiano <j.boggiano@seld.be>
  17. */
  18. class GitProcessor
  19. {
  20. private $level;
  21. private static $cache;
  22. public function __construct($level = Logger::DEBUG)
  23. {
  24. $this->level = $level;
  25. }
  26. /**
  27. * @param array $record
  28. * @return array
  29. */
  30. public function __invoke(array $record)
  31. {
  32. // return if the level is not high enough
  33. if ($record['level'] < $this->level) {
  34. return $record;
  35. }
  36. $record['extra']['git'] = self::getGitInfo();
  37. return $record;
  38. }
  39. private static function getGitInfo()
  40. {
  41. if (self::$cache) {
  42. return self::$cache;
  43. }
  44. $branches = `git branch -v --no-abbrev`;
  45. if (preg_match('{^\* (.+?)\s+([a-f0-9]{40})(?:\s|$)}m', $branches, $matches)) {
  46. return self::$cache = array(
  47. 'branch' => $matches[1],
  48. 'commit' => $matches[2],
  49. );
  50. }
  51. return self::$cache = array();
  52. }
  53. }