PHP 使用执行时间在错误日志中为新手调试PHP

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 使用执行时间在错误日志中为新手调试PHP相关的知识,希望对你有一定的参考价值。

// Do you want to debug?
define('debug',true);
error_reporting(E_ALL);
$start_time = microtime(true);
register_shutdown_function('shutdown');

// Include this function to your functions.inc.php or whatever shared libraries you are using.
function debug($trace,$query = null){
    if(debug){
        $caller=array_shift($trace);
        if(isset($caller['class']))
                error_log("Initiating class: " . $caller['class']);
        if(isset($caller['function']))
                error_log("Calling function: " . $caller['function']);
        error_log("In file: " . $caller['file']);
        error_log("@ line: " .$caller['line']);
        if(isset($query)){
            error_log("Performing Query: " .$query);
        }
        error_log("---");
    }
}

function shutdown() {
    global $start_time;
    error_log("Execution took: ".round((microtime(true) - $start_time),4)." seconds.");
}

// Add the following lines in every function:
if(debug){
    debug(debug_backtrace());
}

// Examples:
function clean($string,$type){
    if(debug){
        debug(debug_backtrace());
    }
    doTask();
}

// You can also log all the queries you are using by using debug($query) like this:
function selectQuery($query){
    if(debug){
        debug(debug_backtrace(),$query);
    }
    $q = mysql_query($query,$this->dblink) // Make sure $this->dblink goes to your MySQL Connection
        or die("MySQL Error: " . mysql_error());
    $result = mysql_fetch_assoc($q);
    return $result;
}


// Result looks like this:
[12-Nov-2010 11:43:36] Initiating class: Db
[12-Nov-2010 11:43:36] Calling function: dblink
[12-Nov-2010 11:43:36] In file: /Users/sadus/Dropbox/Code/classes/db.class.php
[12-Nov-2010 11:43:36] @ line: 8
[12-Nov-2010 11:43:36] ---
[12-Nov-2010 11:43:36] Initiating class: Db
[12-Nov-2010 11:43:36] Calling function: selectQuery
[12-Nov-2010 11:43:36] In file: /Users/sadus/Dropbox/Code/classes/usermanagement.class.php
[12-Nov-2010 11:43:36] @ line: 76
[12-Nov-2010 11:43:36] Performing Query: SELECT * 
                    FROM user
                    WHERE email = '' AND verified = '1' LIMIT 1
[12-Nov-2010 11:43:36] ---
[12-Nov-2010 11:43:36] Execution took: 0.0076 seconds.

以上是关于PHP 使用执行时间在错误日志中为新手调试PHP的主要内容,如果未能解决你的问题,请参考以下文章

php 启用WordPress错误日志调试输出到文件

PHP 创建错误日志csv文件以进行调试

怎么让php打印错误日志?

LNMP环境下配置PHP错误信息提示

在 PHP 中为 MATCH AGAINST 准备的语句不起作用

如何调试从 PHP 文件调用的 Perl