Utilizing debug_backtrace() function for Magento debugging


As promised, back with the 2nd utility function for Magento (printDebugBacktrace).
This function will help you to print the backtrace. As you know that Magento has so many classes and flow/interlinking of those classes’ methods are really vague. So this function will help you to debug/trace in such cases.
printDebugBacktrace function looks like:

public static function printDebugBacktrace($title = 'Debug Backtrace:') {
	$output		= "";
	$output .= "<hr /><div>" . $title . '<br /><table border="1" cellpadding="2" cellspacing="2">';

	$stacks		= debug_backtrace();

	$output .= "<thead><tr><th><strong>File</strong></th><th><strong>Line</strong></th><th><strong>Function</strong></th>".
	foreach($stacks as $_stack)
		if (!isset($_stack['file'])) $_stack['file'] = '[PHP Kernel]';
		if (!isset($_stack['line'])) $_stack['line'] = '';

		$output .=  "<tr><td>{$_stack["file"]}</td><td>{$_stack["line"]}</td>".
	$output .=  "</table></div><hr /></p>";
	return $output;

You need to put the above method in app/Mage.php.
Note: As you see that above method utilizes the PHP’s debug_backtrace() method. But manually calling that function will give you very large string due to large no of complex properties & nested objects in Magento classes, and will be very difficult in tracing. So it’s recommended to use the above-mentioned utility function instead.


Suppose say you are trying to figure out the flow of


Go to that class method and put the following line

public function collect(Mage_Sales_Model_Quote_Address $address)
	echo Mage::printDebugBacktrace(); exit; //add this line just after the opening
	//Mage::log(Mage::printDebugBacktrace(), null, 'backtrace.log'); //or you can even log the backtrace

And when you load the page (my cart) in frontend then you will get the following output:

Output: printDebugBacktrace
Output: printDebugBacktrace

Isn’t that very helpful to know the flow and debug accordingly?
Good Luck with Magento Debugging.


After this article was written, found that we can do the very same thing using the following inbuilt method:


Whose arguments are as:

* Prints or return a backtrace
* @param bool $return      return or print
* @param bool $html        output in HTML format
* @param bool $withArgs    add short argumets of methods
* @return string|bool
public static function backtrace($return = false, $html = true, $withArgs = true)

So now you can simply call as

echo Varien_Debug::backtrace(true, true); exit;
Mage::log(Varien_Debug::backtrace(true, true), null, 'backtrace.log');