prasanna
prasanna

Reputation: 1907

How to record the name of the file/line that called the current function in PHP?

I am writing a lightweight logging class in php. How do I automatically record the filename/function/line number where the function in the Log class is being called from and save the line number and time and stuff without making my users bother with entering $__LINE__ and $__FILE__ every time they call the function. Is there something that I can implicitly call.

Example:

class Log {
static private $instance;
static $logfile;
private function __construct(){
    // doesn't need to do anything
    // one logging object to avoid/control future/potential race conditions
}
public function getInstance(){
    if(!Self::$instance) {
        Self::$instance = new Log();
    } else {
        return Self::$instance;
    }
}

public function criticalLog($string){
    // I want this to be logging line number, filename

}
}

Now I want to be able to something like in say file api.php line number 15

logInstance.criticalLog("This log is important");

In my log file, I'd like to see

12/10/09-11:15 api.php 15 This log is important

Any ideas? I had a look at PEAR and log4php solutions, but they seem pretty heavy for what I want.

Upvotes: 2

Views: 251

Answers (2)

Ben Everard
Ben Everard

Reputation: 13804

Take a look at the debug_backtrace function, it would appear it provides all the information you need:

function, line, file, class, object, type, args

Upvotes: 2

Related Questions