ロギングクラスについてここに別の質問がありますが、呼び出し元のスクリプトの行番号をログファイルエントリに追加できるようにしたかったのです。
__Line __を見たことがありますが、これにより、これが存在する行の行番号がわかります。
例:
a.php
$log = new Logger();
$log->debug('hello'); // Say this is line #20
これで、debug()のLogger.phpクラスで、たとえば行#300で__Line__マジック定数を使用します。スクリプトを実行すると、ログエントリに「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;
}
}