Magento 2 log backtrace
It is very easy to log backtrace in Magento 2. This is very useful if you are currently debugging an issue and have no clue, what classes are involved in your computation. See a list of all calling class methods and find the root of your issue.
Magento 2 log backtrace
The following little script prints a backtrace from Magento 2:
1 2 3 4 | $debugBackTrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); foreach ($debugBackTrace as $item) { echo @$item['class'].@$item['type'].@$item['function']."\n"; } |
You will see the output in your console. This is usable for some test scripts, but not for scripts that are called by web server. Unfortunately you won’t see this output if you click you through checkout for example. With only a small addition, you can log backtrace directly to you debug log. All you need is to inject logger class for this:
1 2 3 4 5 6 7 8 | public function __construct( \Psr\Log\LoggerInterface $logger, ... $debugBackTrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); foreach ($debugBackTrace as $item) { $this->logger->addDebug(@$item['class'] . @$item['type'] . @$item['function']); } ... |
You can place you backtrace lines of code wherever you want in this class. It logs you detailed information which classes and methods are called, before this lines of code comes to execution.
Debugging
With a detailed backtrace in mind, it is easy to find the issue. You can add debugging output in caller classes and also inspect values easily. It is no real time debugging like XDebug, but mostly the only usable method if you have to debug on a live system.
Conclusion
Adding a log backtrace is helpful if you are debugging a part of Magento 2, which you are not that experienced. It shows you a detailed list of things that are called step by step. It helps you to easily find an issue, but also gives you a deeper understanding of how things actually work in Magento 2. You should learn from it and be a better developer.
What other helpful debugging scripts do you know? How do you find issues in Magento 2?