Tag Archive: debug

调试程序往往比编写程序更浪费时间,正如一些有经验的程序员所说,软件的开发应该包括20%的程序编写时间和80%的Debug时间。并且调试程序比编写程序要难2倍。编写巧妙的程序并不一定调试方便。

程序的调试有很多方法,比如最常见的VC之类的IDE都提供加断点,逐步执行,逐段执行的功能。但是这只能针对程序某个微小的片段,对于前期bug的范围的界定并不是很方便。况且对于不满IDE的臃肿,身陷Vim, notepad++, Editplus之类的编辑器之中,我们需要找到更加高效的程序调试和测试方法。

在程序执行的关键点打印Log是一个非常高效的方法,如何打印log进行程序调试呢? 以PHP程序开发为例,需要2个步骤:

1. PHP函数中两个关键的打印变量的方法

print_r var_dump

所以我们可以在关键的地方打印需要的变量。

2. 收集我们在程序中打印的变量

我们可以把程序执行过程中打印的变量逐条写到文本文件里。在程序执行完毕之后进行分析,查找Bug,修正程序。

PHP中打印时间,和变量的程序片段:

function file_log($message) {
    global $file_log_location;
    ob_start();
    echo date("Y-m-d H:i:s \t", time());
    print_r($message);
    echo "\n";
    $var = ob_get_contents();
    ob_end_clean();
    $open=@fopen($file_log_location,"a");
    @fwrite($open,$var);
    fclose($open);
}

应用此段程序还需要对log的存储位置$file_log_location赋值。

在需要的地方插入此片段,执行PHP程序,就会得到所需信息。

但是假如是长时间运行的程序如何在程序执行的过程中就查看到log的信息?相信你已经想到了可以在shell中用

tail -f /var/debug.log

这样总可以看到程序吐出的最新的debug信息。

附件是Drupal中进行debug的一个小的module,做drupal开发的同学可以尝试一下。

Drupal debug module

虽然本文针对PHP开发所言,但是这种方法也适合python,java之类的动态语言的开发。

–EOF–

Tools: Firefox & Firebug or Safari
Library:
function ConsoleLogger(level)
{
this.level=level||4;
this.start=function(){};
this.log=function(msg,level){
level=level||0;
if(level>this.level)return;
if(typeof(console)==’undefined’)return;
try{
switch(level){case 0:console.warn(msg);break;
case 1:console.error(msg);break;
case 2:console.info(msg);break;
case 4:console.debug(msg);break;
default:console.log(msg);break;
}
}catch(e){
try{console.log(msg)}catch(e){}
}
};
this.setLevel=function(level){
this.level=level;return this;
};
this.getLevel=function(){
return this.level;
};
}
Example:
oDbg = new ConsoleLogger(2);
oDbg.log(“warn info: ….”, 0);
oDbg.log(“error info: ….”, 1);
oDbg.log(“info info: ….”, 2);
oDbg.log(“debug info: ….”, 4);

You can get the debug information in the console of Firebug.

Debug javascript manually

try {

YOUR JAVASCRIPT CODE

} catch (e) {
for (myBug in e) {
alert (“e["myBug +"] = “+e[myKey]);
}
}

Surround your JavaScript code with try catch,
run the code in your browser,
then you will see every error in your codes.