PHP从记录事件中获取行号

Phi*_*ord 7 php logging line-numbers magic-constants

好吧,我有一个问题这里为我的日志类,但我希望能够调用脚本的行号添加到日志文件条目.

我见过__Line __但这给了我这行所在行的行号.

例:

a.php只会

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

现在在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;
        }       
    }
Run Code Online (Sandbox Code Playgroud)

编辑: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;
        }       
    }
Run Code Online (Sandbox Code Playgroud)

Art*_*cto 13

你必须使用debug_backtrace它,否则总是将行(with __LINE__)传递给函数.

  • +1注意`debug_backtrace`是slooow,所以它应该只在调试模式下使用. (5认同)