Can I hook a method to my php file, that if any pa

2019-04-14 16:36发布

I am wondering if I can hook a method in a include, that will email me the debug logs if any of my pages (that uses that include) crashed.

Is there a method that is executed after a fatal error?

3条回答
做自己的国王
2楼-- · 2019-04-14 16:49

You can use register_shutdown_function() for this. You pass a function name as a parameter to this function, and that function is called when the application exits, for whatever reason.

You can use this time to catch and log any fatal errors, but you can't recover from them (they are fatal, after all). I think encounter a fatal error within this function, it's game over. There's no logging that.

In your shutdown function, you'll want to check if the shutdown was due to a fatal error and run logging code if it was:

function shutdown() {
  $lastError = error_get_last(); // returns an array with error information:
    switch($lastError['type']){
      case E_ERROR:
      case E_PARSE:
      case E_CORE_ERROR:
      case E_CORE_WARNING:
      case E_COMPILE_ERROR:
      case E_COMPILE_WARNING:
          // log the fatal error
          break;
    }
}
查看更多
叛逆
3楼-- · 2019-04-14 17:00

This should help

Elmah For other PHP

查看更多
叼着烟拽天下
4楼-- · 2019-04-14 17:10

You can catch all errors but fatal errors using set_error_handler(). Unfortunately even "harmless" things like calling undefined functions are fatal and cannot be handled.

However, you can enable error_log in php.ini and set it to log errors to syslog. You'll also get fatal errors in this log.

查看更多
登录 后发表回答