写一个把调试信息输出到磁盘文件的DEBUG程序(原创)
上一篇 /
下一篇 2007-10-02 22:23:43
/ 个人分类:Debug
昨天提到过,在下正在看OPENCART的源代码,随着工作的深入,局面日益复杂起来,写一些如echo,print_r等语句直接把变量显示在浏览器上,不仅干扰了正常的系统显示,因为SESSION的使用,也会造成系统运行时的干扰。要想个办法能把调试信息保存在一个文件里,运行过后调出来慢慢看,不是一个很好的办法吗?
突然想起前两天发到论坛里的一篇文章:http://www.phpchina.com/bbs/thread-37420-1-2.html,里面不是有一个好的调试类吗?找出来一看,果然可以利用上,就搬出来做到一个文件里,代码如下
<?php /* usage: write in: ZFDemo_Log::log("PHP extensions loaded = \n " . implode("\n ", $extensions)); or: ZFDemo_Log::log("The '$ext' extension is required, but not currently loaded by PHP."); ZFDemo_Log::log("Zend_Session.ini=" . print_r($sessionConfig->toArray(), true)); output: ZFDemo_Log::show(); require_once('zfdemo_log.php'); */ class ZFDemo_Log { // very simple running log of "debug" messages to highlight inner workings of demo public static $log = ''; /** * Accumulate log messages, but also append them to a running log file for easy viewing. */ public static function log($msg, $before = null) { static $flushed = false; if ($before) { self::$log = "$msg\n" . self::$log; } else { self::$log .= "$msg\n"; }
$logfile = 'log.txt'; // performance is not an issue, so just sync to disk everytime if (isset($logfile)) { if ($flushed) { file_put_contents($logfile, "$msg\n", FILE_APPEND); } else { file_put_contents($logfile, self::$log); } $flushed = true; } } /* * Useful if you modify the demo, and need to quickly see the debug log in your browser. */ public static function show() { echo "<html><head><title>ZF Demo Debug Log</title></head>\n<body>\n<pre>"; echo htmlentities(self::$log, ENT_QUOTES, 'UTF-8'); echo '</pre></body></html>'; }
public static function get() { return self::$log; } }
|
保存到你正在开发的文件夹中,可以放在一个子目录下,如/DEBUG/zfdemo_log.php,然后在你需要调试的文件里进行调用,例示代码如下:
<pre> <?php require_once('debug/zfdemo_log.php'); $a = array (1, 2, array ("a", "b", "c")); $b = array (3, 4, array ("d", "f", "g")); ZFDemo_Log::log('$a=' . print_r($a, true));
ZFDemo_Log::log('$b=' . print_r($b, true)); ZFDemo_Log::show(); ?> </pre>
|
执行后系统正常运行,然后在同一目录下可以找到一个文本文件log.txt,内容如下:
$a=Array ( [0] => 1 [1] => 2 [2] => Array ( [0] => a [1] => b [2] => c ) ) $b=Array ( [0] => 3 [1] => 4 [2] => Array ( [0] => d [1] => f [2] => g ) ) |
在对复杂的系统进行调试时,这种方法不失高效方便。当然如果需要直接在屏幕上查看调试信息的话,可在相应位置写入代码:
即可实现浏览器上直接显示调试信息。
(当时发贴时,二楼一个家伙马上就说这个教程“误人子弟”,其目的无非是想打压ZF,不过大家可以看到,这个例子中可以提出这么好的调试类代码,怎么说也会对大伙有益吧,如果你觉得这份东东对你有帮助,请留言支持一下吧
)
相关阅读:
- PHP 编码规范 (paged, 2007-9-28)
- 什麼是 JSON (phperwuhan, 2007-9-28)
- PHP获取当前url的函数及服务器变量 (xiaotian_ls, 2007-9-28)
- (转)PHP编码规范 (xiaotian_ls, 2007-9-28)
- 学习、开发计划 (paged, 2007-9-30)
- 看澳洲眼科医生玩转ZendFramework和AJAX (chenz1117, 2007-9-30)
- PHP5盗链函数(referfile) (phperwuhan, 2007-9-30)
- php extends 的问题 (xiongbing528, 2007-10-01)
- 大家无形 (chenz1117, 2007-10-02)
- PHP 的 7 大安全错误(中文版) (avinmo, 2007-10-02)
导入论坛
收藏
分享给好友
管理
举报
TAG:
PHP
技巧
debug
调试
Debug