PHP 从日志事件中获取行号

标签 php logging line-numbers magic-constants

好的,我还有一个问题HERE对于我的日志记录类,但我希望能够将调用脚本的行号添加到日志文件条目中。

我看过 __Line __ 但这给了我所在行的行号。

例子:

a.php

$log = new Logger();
$log->debug('hello'); // Say this is line #20

现在在 debug() 的 Logger.php 类中,我使用 __Line __ Magic Constant 在例如第 300 行。当我运行脚本时,我希望日志条目显示为“第 20 行”,但它显示为“第 300 行”。除了将行号传递给函数之外,还有其他方法可以做到这一点吗?

示例调试类函数

public function debug($message) {
        if(DEBUG) {
            $this->calling_script = $this->getScriptBaseName();
            $this->log_file = LOG_FILE_DIRECTORY."/".$this->calling_script.".log";
            $this->fh = fopen($this->log_file, 'a') or die("Can't open log file: ".$this->log_file);

            if($this->first_run) {
                $this->log_entry = "\n[" . date("Y-m-d H:i:s", mktime()) . "][debug][line:".__LINE__."]:\t".$message."\n";
            } else {
                $this->log_entry = "[" . date("Y-m-d H:i:s", mktime()) . "][debug][line:".__LINE__."]:\t".$message."\n";
            }       
            fwrite($this->fh, $this->log_entry);
            fclose($this->fh);

            $this->first_run = false;
        }       
    }

编辑:debug_backtrace() 效果很好!!!在下面工作

public function debug($message) {
        if(DEBUG) {
            $debug_arr = debug_backtrace();
            $this->calling_script = $this->getScriptBaseName();
            $this->log_file = LOG_FILE_DIRECTORY."/".$this->calling_script.".log";
            $this->fh = fopen($this->log_file, 'a') or die("Can't open log file: ".$this->log_file);

            if($this->first_run) {
                $this->log_entry = "\n[" . date("Y-m-d H:i:s", mktime()) . "][debug]:\t".$message." [line:".$debug_arr[0]['line']."]\n";
            } else {
                $this->log_entry = "[" . date("Y-m-d H:i:s", mktime()) . "][debug]:\t".$message." [line:".$debug_arr[0]['line']."]\n";
            }       
            fwrite($this->fh, $this->log_entry);
            fclose($this->fh);

            $this->first_run = false;
        }       
    }

最佳答案

你必须使用 debug_backtrace为此,否则始终将行(使用 __LINE__)传递给函数。

关于PHP 从日志事件中获取行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3215447/

相关文章:

PHP PDO 准备查询拒绝正确执行 - 转义问题?

php - 如何列出数据库中的重复条目

适用于 Node 和浏览器的 JavaScript 日志记录库

java - 与库一起使用的不同记录器

c++ - 如何将行号传递给异常?

linux - GDB 找不到行号

php - 如何重新生成 crud -- Doctrine :generate:crud after editing the entity

python - 我可以收到有关我的 GAE 应用程序错误的电子邮件通知吗?

java - 文本编辑器分隔符行号重叠和长行标记

PHP/MYSQL - 找不到此代码发送邮件两次以上的原因