我正在为我编写的某些脚本创建调试/日志记录类。 目前,我有以下内容:
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";
}
}
基本上,这使我可以使用可变数量的参数来调用log方法,并记录每个参数(我已从代码中删除了格式设置和实际的日志写操作,以便于阅读)。
$test='goodby';
$log=new \loggy();
$log->log('hello', $test);
exit();
输出以下内容:
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
我想找到一种方法来提取传递给log方法的字段,这样我就可以得到如下输出:
File : public/index.php - Line 35 : String : hello
File : public/index.php - Line 35 : Var : $test : goodby
是否有关于从代码调用行提取参数名称的最佳方法的建议?
想法是减少日志记录行,例如:
$log->log('String ='.'hello', '$test='.$test);
我知道我可以做类似的事情:
$paramStart=strpos($fileLine, $function)+4;
$paramEnd=strpos($fileLine, ')');
$paramLength=$paramEnd-$paramStart;
$string=substr($fileLine, $parmStart, $paramLength);
$params=explode($string, ',');
但是那段代码非常不可靠,并且在调用log方法的行上强制采用非常严格的规则。
编辑:
建议:original variable name passed to function? 回答了这个问题,但仍然存在将参数与源代码分离的问题:
debug($param1, "i love PHP scrip\'s", $param2, 'but I hate, trying to debug them! as it costs $\'s in time');
我可以提取一个字符串:
$param1, "i love PHP scrip\'s", $param2, 'but I hate, trying to debug them! as it costs $\'s in time'
从源代码开始,但是找不到可靠地分离每个参数的方法,以便给我一个像这样的数组:
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'
);
如您所见,上面的示例意味着我不能只将字符串拆分为',',还需要考虑转义字符。