Monday, October 12, 2009

printing the backtrace in a complex PHP application

the PHP debug_backtrace [man] function is very useful to understand where a function/method is called.

It prints the back trace of the code.

Example: In the framework I'm currently using there are ORM classes to access the DB. So, it takes long to understand where the query is launched when needed. Solution: save in a global variable (or in a field of the class) the list of the queries launched and the code that has launched each query.


Code:


class DB {
# ...
public function query($query) {
if (
DEBUG_MODE) { ##
$_dbt = debug_backtrace();
$_fromFile = isset( $_dbt[0]['file']) ? str_replace(_ROOT, "",$_dbt[0]['file']) : "";
$_fromLine = isset( $_dbt[0]['line']) ? $_dbt[0]['line'] : "";
$_launchedFrom = "launched from $_fromFile:$_fromLine";
$this->logQueries[] = "[$query][$_launchedFrom]";
# ..query.
}
}
# ...
}



Example of result:


Array
(
[
0] => [set names utf8][launched from C:\wamp\www\dev\index.php:68]
[
1] => [SELECT * FROM `Setting` WHERE `id` = 1][launched from \class\Setting.class.php:20]
[
2] => [SELECT id FROM `User`WHERE id = 293968 LIMIT 1][launched from \class\User.class.php:598]
[
3] => [SELECT * FROM `User` WHERE `id` = 293968][launched from \class\User.class.php:45]
[
4] => [SELECT f.store_id FROM `Store_Monthly_Featured` f ORDER BY f.order ASC][launched from \class\Store_Monthly_Featured.class.php:16]
)


Useful function to print only line and number


function debug_backtrace_filelines() {

$ret = array();
$b = debug_backtrace();
foreach (
$b as $elements) {
$ret[] = $elements['file'].':'.$elements['line'];
}
}

No comments:

Post a Comment

 

PHP and tips|PHP