doudou3716 2012-01-24 17:01 采纳率: 100%
浏览 94

PHP:生产中的FATAL错误的日志堆栈跟踪

I want to log every fatal errors, even timeout and others E_ERRORS ones. I use set_error_handler and shutdown function, but with the last one I cannot have the stacktrace. Is there any way to have it?

I want to log fatals errors on a production server to help resolving bugs wich occurs only in production. I know, xdebug on dev servers must be enough, but it is not. Maybe we can use xdebug with the minimum of options activated, or a stripped version of it to add stack trace to error log?

This code print error information if one error occur, even a timeout.

<?php
function shutdown()
{
    $a=error_get_last();
    if($a!==null) print_r($a);  
}
register_shutdown_function('shutdown');
  • 写回答

3条回答 默认 最新

  • doushoubu5360 2012-01-24 17:15
    关注

    You won't get a stack trace on the fatal error because "FATAL" means script execution stops immediately, i.e. the trace can't be generated through the usual channels. So, if you have set a custom error handler to throw exceptions, it won't be invoked for fatal errors as per the PHP manual:

    The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

    The easiest way to get info about what happened in the fatal error (short of turning display_errors on, which isn't an option in production environments) is to manually build the error information yourself in the shutdown handler. Also, I wouldn't use xdebug on a production server ... it's for debugging your development environment and will add unnecessary overhead in a production environment.

    So, modifying your shutdown handler you could do something like this:

    function shutdown()
    {
      if ( ! $err = error_get_last()) {
        return;
      }
    
      $fatals = array(
        E_USER_ERROR      => 'Fatal Error',
        E_ERROR           => 'Fatal Error',
        E_PARSE           => 'Parse Error', 
        E_CORE_ERROR      => 'Core Error',
        E_CORE_WARNING    => 'Core Warning',
        E_COMPILE_ERROR   => 'Compile Error',
        E_COMPILE_WARNING => 'Compile Warning'
      );
    
      if (isset($fatals[$err['type']])) {
        $msg = $fatals[$err['type']] . ': ' . $err['message'] . ' in ';
        $msg.= $err['file'] . ' on line ' . $err['line'];
        error_log($msg);
      }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么