简体   繁体   中英

PHP custom error handler log to output

I have a script that will run on server daily to download data from a resource with no HTML output. By default PHP will output my script errors to php_error.log and to the output window in NetBeans.

I have created a user error handler:

// user defined error handling function
function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars) 
{
    error_log($errmsg, 3, "logs/aem.log");     
    switch ($errno) {
    case E_ERROR:
        exit("Error grave $errmsg at $filename:$linenum");
        break;
    case E_USER_ERROR:
        exit("Error grave $errmsg at $filename:$linenum");
        break;
    }
}

error_reporting(0);
set_error_handler('userErrorHandler');

I include this file in my main script and everything goes fine.

While I develop the app I would like to continue seeing the error messages on Output screen in Netbeans as well as keeping the error log files (as the default handler does). I have tried changing the value of error_reporting or adding additional error_log functions trying the following values:

error_reporting(E_ALL | E_STRICT);
error_reporting(-1);
error_log($errmsg, 0);`

But I never get the error on the output unless I remove include('mycustomhandler'); from the file.

How can I emulate the behavior of the standard error handler?

You should try to use output to stderr (I guess netbeans parses it). For example:

fprintf( STDERR, "Normal error message %s\n", "With nested info");

For logging errors you may use error_log() (maybe will handle output to netbeans too) or try to parse error_log from php.ini ( ini_get() ).

However I guess php uses internaly syslog() . So your error handler should look like:

// Logging 
function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars){
  $logLevel = 0;
  $label = '';
  $exit = false;

   switch( $errno){
     case E_ERROR:
     case E_USER_ERROR:
       $label = 'Critical error';
       $exit = true;
       $logLevel = LOG_ERR;
     break;

     // ...
   }

   $message = "$label: on line ... file, error string...";
   if( $logLevel){
     syslog( $logLevel, $message);
   }

   if( !ini_get( 'display_error') && $exit){
     die( 'Fatal error occured.');
   }

   if( $label){
      echo $message; // You're responsible for how error is displayed
   }

   if( $exit){
     die();
   }
}
error_reporting( E_ALL);

Ask questions in comments if I didn't hit what you were asking

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM