In magento 1.x we can use backtrace like

echo Varien_Debug::backtrace(true, true); exit;

How can we use this facility in Magento 2?


You can use debug_backtrace() as I added below.

$debugBackTrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
foreach ($debugBackTrace as $item) {
    echo @$item['class'] . @$item['type'] . @$item['function'] . "\n";

For reference please check dev\tests\api-functional\framework\Magento\TestFramework\TestCase\Webapi\Adapter\Rest\DocumentationGenerator.php

  • 1
    I edited your answer. There was a piece of incorrect syntax, also I changed it to have better output (I used @ to ignore warnings, for instance when 'class' doesn't exist) – 7ochem Jan 3 '17 at 11:45
  • 1
    @krishnaijjadaati95Dev thanks for the answer it works for me – Ashish Madankar M2 Professiona Jan 3 '17 at 12:26

In the logger classes of Magento 2, the debug_backtrace method is not used directly.

So the Magento 2 way of doing backtrace is to use the Magento\Framework\Debug class (which is the equivalent of the M1 Varien_Debug class) and call the backtrace() method:

 * Prints or returns a backtrace
 * @param bool $return      return or print
 * @param bool $html        output in HTML format
 * @param bool $withArgs    add short arguments of methods
 * @return string|bool
public static function backtrace($return = false, $html = true, $withArgs = true)
    $trace = debug_backtrace();
    return self::trace($trace, $return, $html, $withArgs);
  • 2
    This should be the accepted answer. – mpchadwick Apr 19 '17 at 16:10

In any PHP application you can just do:

$e = new \Exception();
echo '<pre>';

Due to name spacing in M2, you need to use new \Exception(); instead of just new Exception();

  • thanks for the answer i tried that but it says class Exception' not found in path of my calling class – Ashish Madankar M2 Professiona Jan 3 '17 at 11:29
  • @AshishMadankar - see edit! – Paras Sood Jan 3 '17 at 11:35
  • Or shorter: print_r((new \Exception())->getTraceAsString()); (since PHP 5.4, so safe to use in M2) – 7ochem Jan 3 '17 at 11:39
  • 1
    @ParasSood its also working – Ashish Madankar M2 Professiona Jan 3 '17 at 12:26

You can use PHP function debug_backtrace to debugging in Magento.

Use following code in magento to track the issue by using debug_backtrace

foreach (debug_backtrace() as $_stack) {
    echo ($_stack["file"] ? $_stack["file"] : '') . ':' .
        ($_stack["line"] ? $_stack["line"] : '') . ' - ' .
        ($_stack["function"] ? $_stack["function"] : '').'<br/><hr/>';

You will see the debug backtrace that will allow you to define the issue source and you will get an idea how to fix the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.