views:

49

answers:

2

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.

+2  A: 

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
ILMV
Seconded, debug_backtrace() is the way to go. In my experience, though, it is very expensive, and in production use, I tend to turn it off. But this applies to all logging solutions that probably all rely on debug_backtrace().
Pekka
Yup, I usually use it for debugging and switch it off when the system goes live.
ILMV
Thanks, I haven't tried it yet but makes sense from the examples.
pvsnp
A: 

Magic constants : http://www.php.net/manual/en/language.constants.predefined.php

peperg
Won't help here, as they will return the criticalLog() function's file and line. He would have to include the constants as parameters to the call, which is doable but cumbersome.
Pekka