一种debug方法的实现

据说程序的开发成本占20%,维护成本占80%,而维护的主要方式之一依靠的是log输出。

输出log有很多方式,各种开发语言都有不同的设施来满足这一功能。

在PHP中,可以这么实现一个debug功能。其主要功能是输出什么时间在什么位置(程序名、函数名)输出了标记为xxx的某个对象$obj的打印形式的描述信息。

function debug($obj, $tag=null, $output=null);
# $obj 是待输出和跟踪的对象,可能是string,也可能是array、hash等不同的数据结构;
# $tag 是用于标记待输出对象的字符串,一般用于过滤相关输出内容;默认 $tag 为null;
# $output 类似loglevel, 但又不同,通常 $output==null, 表示在后天输出相关日志,与 error_log 函数类似; $output==1时,在后台和前端同事输出相关测试信息;$output==2时,根据PHP中的backtrace信息,输出更多内容。
# 调用例子:
# debug($aHash); # 在后台输出一个hash变量的内容;使用 -GWA2 的 WebApp->toString 方法或者 -PHP 内置的 serialize ;
# debug($aHash, ‘aHash’);  # 在输出中增加识别标记字符 ‘aHash’;
# debug($aHash, ‘aHash’, 2); # 同时在前端和后台输出相关内容,然后附带 -PHP 的backtrace信息.

源码 source:

# write log in a simple approach
# by wadelau@ufqi.com, Sat Oct 17 17:38:26 CST 2015
# e.g.
# debug($user);
# debug($user, ‘userinfo’); # with tag ‘userinfo’
# debug($user, ‘userinfo’, 1); # with tag ‘userinfo’ and in backend and frontend
function debug($obj, $tag=”, $output=null){
$caller = debug_backtrace();
if(is_array($obj)){
if(isset($user)){
$s .= $user->toString($obj);
}
else{
$s .= serialize($obj);
}
}
else{
$s .= $obj;
}

if($tag != ”){
$s = ” $tag:[$s]”;
}
$callidx = count($caller) – 2;
$s .= ‘ func:[‘.$caller[$callidx][‘function’].’] file:[‘.$caller[$callidx][‘file’].’]’;

if($output != null){
if($output == 0){ # in backend only
error_log($s);
}
else if($output == 1){ # in backend and frontend
error_log($s);
print $s;
}
else if($output == 2){ # in backend and frontend with backtrace
$s .= ” backtrace:[“.serialize($caller).”]”;
error_log($s);
print $s;
}
}
else{
error_log($s); # default mode
}

}

其他版本的语言也可参考此行为,自行实现。这一功能已经更新到新版的 -gMIS 和 -GWA2 的源码中.

 

此条目发表在-gMIS, -GWA2, 服务器运维, 编程技术, 计算机技术分类目录,贴了, , , 标签。将固定链接加入收藏夹。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

Captcha Code