Skip to content

Instantly share code, notes, and snippets.

@sycobuny
Created January 17, 2014 16:28
Show Gist options
  • Save sycobuny/8476404 to your computer and use it in GitHub Desktop.
Save sycobuny/8476404 to your computer and use it in GitHub Desktop.
Dump PHP variables into the error log instead of the page when debugging
<?php
/**
* Dump a variable to error_log instead of the main page
*
* To do debugging, it's often preferable to stick output into the
* error log rather than the main page, in case you might forget to remove
* a statement (it does happen) - but you can't do `var_dump()` or
* `print_r()` to output, or at least you couldn't before. This will get
* the output of those functions and send them to error_log(), reformatted
* so that each line gets its own output, since many configurations will
* result in literal newlines being converted to "\n" in the logs,
* resulting in messy output. Each line is also prefixed with a string:
*
* "DUMP from $file:$line:"
*
* This way you can both easily grep for the output you're looking for, as
* well as quickly find where you've put in a debugging statement, again
* in case you've left it in by accident.
*
* The default is to use `var_dump()`, as it is far more verbose than
* `print_r()`, though the output isn't as clean. If you're trying to
* debug a particular object and don't care to know the difference between
* various `FALSE`-y values, and other information such as string length,
* you can pass a `true` value after your variable, and the function will
* switch to using `print_r()` instead.
*
* @param mixed $var The variable or expression to dump
* @param boolean $print (optional) Whether to dump with print_r()
* @return void
*/
function error_dump($var, $printr = false) {
ob_start();
if ($printr) {
print_r($var);
}
else {
var_dump($var);
}
$output = explode("\n", ob_get_clean());
$trace = debug_backtrace();
$location = $trace[0]['file'] . ':' . $trace[0]['line'];
foreach ($output as $x => $line) {
error_log("DUMP from $location: $line");
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment