I'm building a basic error logging feature in my application, where I just record a custom message like "product ID was missing" and record it in the DB. Is there any way I can dynamically capture from which class or function the error was triggered (ie the function from where log_error() was called), or the line number?
From PHP 5.2.0 on, there is error_get_last(). (Cheers @Gordon) It will give you an array with all the information about the last error:
Array
(
[type] => 8
[message] => Undefined variable: a
[file] => C:\WWW\index.php
[line] => 2
)
A more flexible approach to handling errors in general is defining a custom error handler.
A custom error handler accepts the following parameters:
handler ( int $errno, string $errstr [, string $errfile
[, int $errline [, array $errcontext ]]] )
Backtraces The most information you'll get with a backtrace - useful in many situations. To do that, combine the error handler with debug_backtrace(). It will give you an array with every point in the call stack (i.e. which function called which called which called which... until the error.)
Stack traces cost a lot of computing time, so you should not use them in production and have a switch to turn them on and off.
If you are using Exceptions, you might have a way : there is a getLine()
method in the Exception
class, that'll allow you to know from where the exception was thrown.
If you are using functions, there is no "real" way ; a solution could be to use the debug_backtrace
function -- see the manual page for an example of the informations it can get you...
you can easy make a code appear in error like that
$get = mysql_query("SELECT * FROM 'table' where id='.....'");
$row = mysql_fetch_array($get);
if (!$row)
{
//record the data now
}