Question
I’ve created a logging class and want to stamp each line with the class::method that called the static method of the logger class.
Is it possible to tell what called the current method in PHP?
Solution
Thanks for the help. Here’s the PHP code for my logging method.
/**
* Writes a line into the log.
* @param string $level The logging level.
* @param string $message The message.
*/
protected static function write($level,$message)
{
self::scope_init();
if(self::$scope[$level])
{
$e = new Exception;
$stack = $e->getTrace();
$caller = '';
if(isset($stack[2]))
{
$class = isset($stack[2]['class']) ? $stack[2]['class'] : false;
$method = isset($stack[2]['function']) ? $stack[2]['function'] : '';
if($class !== false)
{
$caller = $class.'::'.$method;
}
else
{
$caller = $method;
}
}
$caller = substr(str_pad($caller,20),0,20);
$msg = date('m.d.y h:i:sa').' ['.$level.'] ['.$caller.'] '.$message;
self::$lines[] = $msg;
echo "$msg\n";
}
}
This answer about printing stack traces gives a way to access the stack trace. From there, you can get just the second-to-last item and record that.