views:

56

answers:

4

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?

+1  A: 

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.

Pekka
I've upvoted already, but add http://de.php.net/manual/en/function.error-get-last.php to the list please.
Gordon
@Gordon done, cheers.
Pekka
+1  A: 

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...

Pascal MARTIN
A: 

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
    }
moustafa
A: 
Mark Tomlin