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?
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
";
}
}
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.
$e = new Exception;
var_dump($e->getTraceAsString());
#2 /usr/share/php/PHPUnit/Framework/TestCase.php(626): SeriesHelperTest->setUp()
#3 /usr/share/php/PHPUnit/Framework/TestResult.php(666): PHPUnit_Framework_TestCase->runBare()
#4 /usr/share/php/PHPUnit/Framework/TestCase.php(576): PHPUnit_Framework_TestResult->run(Object(SeriesHelperTest))
#5 /usr/share/php/PHPUnit/Framework/TestSuite.php(757): PHPUnit_Framework_TestCase->run(Object(PHPUnit_Framework_TestResult))
#6 /usr/share/php/PHPUnit/Framework/TestSuite.php(733): PHPUnit_Framework_TestSuite->runTest(Object(SeriesHelperTest), Object(PHPUnit_Framework_TestResult))
#7 /usr/share/php/PHPUnit/TextUI/TestRunner.php(305): PHPUnit_Framework_TestSuite->run(Object(PHPUnit_Framework_TestResult), false, Array, Array, false)
#8 /usr/share/php/PHPUnit/TextUI/Command.php(188): PHPUnit_TextUI_TestRunner->doRun(Object(PHPUnit_Framework_TestSuite), Array)
#9 /usr/share/php/PHPUnit/TextUI/Command.php(129): PHPUnit_TextUI_Command->run(Array, true)
#10 /usr/bin/phpunit(53): PHPUnit_TextUI_Command::main()
#11 {main}"
Do you mean this one: apd-callstack?
You can use the __METHOD__
magic constantbinside of the calling method