Search code examples
phperror-handlingerror-logging

How to put custom variables into PHP error logs


I want to include certain server information in the error logs. Is there a way to force PHP to include $_SERVER['SERVER_ADDR'] (or any other variable) into the log entry? So for example the log would be:

[08-Apr-2015 16:58:33] 125.60.12.1 PHP Fatal error: Call to undefined function a() in /index.php on line 5

instead of

[08-Apr-2015 16:58:33] PHP Fatal error: Call to undefined function a() in /index.php on line 5


Solution

  • Error handler

    The best way to get more information for an error is to create your own error handler

    This example outputs the standard error information plus all variables in use at the time.

    This particular function will contain sensitive information so we added a line to remove things like passwords.

    $dev=true;  //dev pc
    
    function error_function($err_level,$err_msg,$err_file,$err_line,$err_context)
    {
        global $dev;
        $err_stg="<br />
        ############################<br />
        <b>Error level:</b> $err_level<br />
        <b>Message:</b>     $err_msg<br />
        <b>File:</b>        $err_file<br />
        <b>On line:</b>     $err_line<br />
        ############################<br /><br />";
    
        //convert array to string
        $err_stg.=serialize($err_context);
    
        //remove sensitive information
        $pos=strpos($err_stg,'MYSQL_PASSWORD');
        if($pos){ $err_stg=substr($err_stg,0,$pos).substr($err_stg,$pos+40); }
    
        if($dev)  //if on dev pc echo error
        {
            echo $err_stg;
        }
        else //if live on site save error to file
        {
            error_log($err_stg,3,"error_file_secret.html");
        }
    }
    

    Set this function as the error handler

    set_error_handler("error_function",E_ALL);
    

    Customise this function to suit your needs.