IntrospectionProcessor.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 line/file:class/function where the log message came from
  14. *
  15. * Warning: This only works if the handler processes the logs directly.
  16. * If you put the processor on a handler that is behind a FingersCrossedHandler
  17. * for example, the processor will only be called once the trigger level is reached,
  18. * and all the log records will have the same file/line/.. data from the call that
  19. * triggered the FingersCrossedHandler.
  20. *
  21. * @author Jordi Boggiano <j.boggiano@seld.be>
  22. */
  23. class IntrospectionProcessor
  24. {
  25. private $level;
  26. private $skipClassesPartials;
  27. private $skipFunctions = array(
  28. 'call_user_func',
  29. 'call_user_func_array',
  30. );
  31. public function __construct($level = Logger::DEBUG, array $skipClassesPartials = array())
  32. {
  33. $this->level = Logger::toMonologLevel($level);
  34. $this->skipClassesPartials = array_merge(array('Monolog\\'), $skipClassesPartials);
  35. }
  36. /**
  37. * @param array $record
  38. * @return array
  39. */
  40. public function __invoke(array $record)
  41. {
  42. // return if the level is not high enough
  43. if ($record['level'] < $this->level) {
  44. return $record;
  45. }
  46. $trace = debug_backtrace();
  47. // skip first since it's always the current method
  48. array_shift($trace);
  49. // the call_user_func call is also skipped
  50. array_shift($trace);
  51. $i = 0;
  52. while (isset($trace[$i]['class']) || in_array($trace[$i]['function'], $this->skipFunctions)) {
  53. if(isset($trace[$i]['class'])) {
  54. foreach ($this->skipClassesPartials as $part) {
  55. if (strpos($trace[$i]['class'], $part) !== false) {
  56. $i++;
  57. continue 2;
  58. }
  59. }
  60. } elseif(in_array($trace[$i]['function'], $this->skipFunctions)) {
  61. $i++;
  62. continue;
  63. }
  64. break;
  65. }
  66. // we should have the call source now
  67. $record['extra'] = array_merge(
  68. $record['extra'],
  69. array(
  70. 'file' => isset($trace[$i - 1]['file']) ? $trace[$i - 1]['file'] : null,
  71. 'line' => isset($trace[$i - 1]['line']) ? $trace[$i - 1]['line'] : null,
  72. 'class' => isset($trace[$i]['class']) ? $trace[$i]['class'] : null,
  73. 'function' => isset($trace[$i]['function']) ? $trace[$i]['function'] : null,
  74. )
  75. );
  76. return $record;
  77. }
  78. }