PHP get line number from logging event

主宰稳场 提交于 2019-12-05 23:25:23

问题


Ok I have another question HERE for my Logging Class but I wanted to be able to add the line number of the calling script to the log file entry.

I have seen __Line__ but this gives me the line number of the line where this is at.

Example:

a.php

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

Now in my Logger.php class in the debug() I use the __Line__ Magic Constant on for example line #300. When I run the script I would like the log entry to read 'on line 20' but it read 'on line 300'. Besides passing the line number to the function is there any other way I could do this?

Example debug class function

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;
        }       
    }

EDIT: debug_backtrace() works great!!! Working below

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;
        }       
    }

回答1:


You'll have to use debug_backtrace for this or else always pass the line (with __LINE__) to the function.




回答2:


Have you seen debug_backtrace()? I'm not sure of its overhead though.



来源:https://stackoverflow.com/questions/3215447/php-get-line-number-from-logging-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!