Log caught exception with stack trace

前端 未结 4 1056
逝去的感伤
逝去的感伤 2020-12-24 05:13

If I don\'t catch an exception in PHP, I get a helpful error message in my error.log file with a stack trace. For example, if I run:



        
相关标签:
4条回答
  • 2020-12-24 05:32

    We use Monolog to do the logging in our application. Monolog has a formatter that can print stack traces. To log exceptions with traces, we use a LineFormatter and call includeStacktraces() on it. (code below)

    $handler = new \Monolog\Handler\StreamHandler(STDOUT);
    
    $lineFormatter = new \Monolog\Formatter\LineFormatter();
    $lineFormatter->includeStacktraces();
    
    $handler->setFormatter($lineFormatter);
    
    $logger = new \Monolog\Logger('root', [$handler]);
    
    try {
        //do some throwing
    } catch (Exception $e) {
        //do some logging, add exception to context
        $logger->error($e->getMessage(), ['exception' => $e]);
    }
    
    0 讨论(0)
  • 2020-12-24 05:41
    error_log($e);
    

    does what you want. It logs exactly the same thing that would have been logged if you didn't catch the exception, minus the word 'Uncaught' at the beginning. It does this because that's what the Exception class's __toString() magic method returns.

    You can do this in a catch block:

    try {
        foo();
    } catch (Exception $e) {
        error_log("Caught $e");
    }
    

    Or in the exception handler:

    set_exception_handler(function($exception) {
        error_log($exception);
        error_page("Something went wrong!");
    });
    
    0 讨论(0)
  • 2020-12-24 05:43

    You can use the methods from PHP's base Exception class.

    Use getMessage to get the message Oh no! and use getTraceAsString to get a formatted trace.

    0 讨论(0)
  • 2020-12-24 05:43

    You can use http://php.net/manual/en/function.set-exception-handler.php to register a callback function which would get the message from $e->getMessage(); and dump it to file.

    0 讨论(0)
提交回复
热议问题