I am creating a debugging/logging class for some of the scripts that i write. Currently I have the following :
public function log()
{
$funcArgs = func_get_args();
$args = array_shift($funcArgs);
$debug = '';
$bt = debug_backtrace();
// OK lets extract the data
$file = $bt[0]['file'];
$line = $bt[0]['line'];
$function=$bt[0]['function'];
$fileContents = file($file, FILE_IGNORE_NEW_LINES);
$fileLine = $fileContents[$line-1];
unset($fileContents);
$debug = 'File :' . $file . ' - Line :' . $line . ' - Command :'
. $fileLine . ' -> ';
foreach ($funcArgs as $index => $arg) {
$output = print_r($arg, true);
}
echo $debug . $output."\n";
}
}
This basically allows me to call the log method with a variable number of parameters and have each one logged (I have removed the formatting and actual log writing from the code to make it easier to read).
$test='goodby';
$log=new \loggy();
$log->log('hello', $test);
exit();
Outputs the following :
File :/var/www/public_html/index.php - Line :35 - Command :$log->log('hello', $test); -> hello
File :/var/www/public_html/index.php - Line :35 - Command :$log->log('hello', $test); -> goodby
I want to find a way to extract the fields that are passed to the log method, so i can get an output like:
File : public/index.php - Line 35 : String : hello
File : public/index.php - Line 35 : Var : $test : goodby
Any recommendations on the best way to extract the parameter names from the calling line of code?
Idea is to cut down on logging lines like :
$log->log('String ='.'hello', '$test='.$test);
I know i can do something like :
$paramStart=strpos($fileLine, $function)+4;
$paramEnd=strpos($fileLine, ')');
$paramLength=$paramEnd-$paramStart;
$string=substr($fileLine, $parmStart, $paramLength);
$params=explode($string, ',');
But that chunk of code is very unreliable and forces very strict rules on how and what can be on a line that calls the log method.
EDIT :
It has been suggested that : original variable name passed to function? Answers this question, but it still leaves the issue of separating the parameters from the source code :
debug($param1, "i love PHP scrip\'s", $param2, 'but I hate, trying to debug them! as it costs $\'s in time');
I can extract a string :
$param1, "i love PHP scrip\'s", $param2, 'but I hate, trying to debug them! as it costs $\'s in time'
from the source code, but cant find a way of reliably separating each of the parameters to give me an array like :
array(
0 => '$param1',
1 => 'i love PHP script`s',
2 => '$param2',
3 => 'but I hate, trying to debug them! as it costs $\'s in time'
);
As you can see, the above example means I can't just split the string on ',' and need to be able to take into account the escaped characters as well.