I often encounter problems with the typical approach of using var_dump (or Zend_Debug::Dump) to trace through PHP code:
- Does not work on a page that has to redirect to another page.
- Results are difficult to see if the page is queried through AJAX.
- The crash may happen so utterly that no data is actually output, or it’s well hidden, or otherwise destroyed by output buffering mishaps.
- I have to look around the page to find it, and it also destroys my page layout.
The other possibility commonly used is to use error_log or log or printing to stderr or printing to a file, all of which rely on access to the server or setting up a way of displaying the data and filtering through it to see only relevant information.
I could bring in some logging facility from a framework (such as Symphony or Zend, which has a nice one), but I’d rather not add overweight dependencies—the Zend_Log_Writer_Firebug setup is kind of scary if you’re not already using enough bits of Zend to make it worth it.
So, I set out to design a system that would make things simpler. It works by sending ‘console.log()’ instructions to Firebug to display whatever it needs to display, and keeping things in the session until they can be displayed.
The code:
function jslog()
{
if (defined('NO_JSLOG'))
return;
$args = func_get_args();
if (empty($args)) {
return create_function('$x',
'if (strpos($x,"</head>") > 0){
$s = "<script type=text/javascript>";
$e = "</script></head>";
$x = str_replace("</head>",$s.$_SESSION["jslog"].$e,$x);
$_SESSION["jslog"] = "";
} return $x;');
}
$_SESSION['jslog'] .=
'console.log('.implode(',',array_map('json_encode',$args)).');';
}
Nothing overly complex. Initialization happens as a simple ob_start(jslog()), and everything can be disabled with a well-timed define('NO_JSLOG','') if you don’t have Firebug running. Typical usage includes being echo-like:
jslog("Hello");
Being var_dump-like:
jslog($_POST);
Being printf-like:
jslog('Earned $%.2f today', $dollars);
Being the best of both worlds:
jslog('My session is %o and my post is %o', $_SESSION, $_POST);
Displayed objects are converted to JSON and sent to Firebug, where they can be explored with the nifty DOM explorer tab that is so much easier to use than looking at var_dumped data.
Hi. I'm Victor Nicollet,
Recent Comments