php - 记录所有执行的行

标签 php

是否有一种简单的方法(除了在每一行之后粘贴 fwrites)让 PHP 将每行执行的行写入日志?

最佳答案

虽然我同意@gnif 因为调试器最适合它,但我仍然会回答你的问题,因为这是可能的(不完美,但可能)。

假设您有以下代码:

sometest.php

<?php

declare(ticks=1);

include_once 'debug.php';

$a = 'foo';
$b = 'bar';
$c = $a . $b;
$d = $e = "hello";
strlen($d);

include 'somefile.php';

somefile.php

<?php

$hello = 'world';

因此,sometest.php 包含以下文件 (debug.php):

<?php

register_tick_function(function(){
    $backtrace = debug_backtrace();
    $line = $backtrace[0]['line'] - 1;
    $file = $backtrace[0]['file'];

    if ($file == __FILE__) return;

    static $fp, $cur, $buf;
    if (!isset($fp[$file])) {
        $fp[$file] = fopen($file, 'r');
        $cur[$file] = 0;
    }

    if (isset($buf[$file][$line])) {
        $code = $buf[$file][$line];
    } else {
        do {
            $code = fgets($fp[$file]);
            $buf[$file][$cur[$file]] = $code;
        } while (++$cur[$file] <= $line);
    }

    $line++;
    echo "$code called in $file on line $line\n";
});

registers a tick function , 还有 declares the tick interval .它将跟踪使用回溯调用的文件/行。

现在,如果我们执行 sometest.php,我们将得到:

include_once 'debug.php';
 called in sometest.php on line 5
$a = 'foo';
 called in sometest.php on line 7
$b = 'bar';
 called in sometest.php on line 8
$c = $a . $b;
 called in sometest.php on line 9
$d = $e = "hello";
 called in sometest.php on line 10
strlen($d);
 called in sometest.php on line 11
$hello = 'world';
 called in somefile.php on line 3
include 'somefile.php';
 called in sometest.php on line 13

您可以看到 somefile.php 包含在最后,即使它是在 $hello = 'world' 之前调用的。这是因为 tick 函数将在该行的包含完成时被调用,而不是在它开始时被调用。

此外,在函数/方法声明中调用 tick 函数:

<?php

function foo() {
    return 'bar';
}

foo();

会给你这样的东西:

}
 called in somefunc.php on line 5   # this is the function declaration
foo();
 called in somefunc.php on line 7   # this is the function call

注意:使用 ticks 时要小心,因为在 5.3.0 之前,线程 Web 服务器不支持它。

关于php - 记录所有执行的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6294122/

相关文章:

php - 持久化新实体 onFlush

php - 使用锁表时事务+回滚

javascript - 尝试更改表单提交上我的提交输入的值

php - 以正确的顺序递归父项以从 MySQL 表中删除

php - 两个 SELECT 语句合并为一个 SQL

javascript - jquery在单击查询中的多个条目时显示div

php - Laravel:从 View 添加字段(用户:批量可分配属性)

PHP/MySQL Ticket Response - 在数据库中存储电子邮件响应?

php - 获取电子邮件引荐地址

php - 从网页提取的数据/文本不会插入到 mysql 数据库中