How can I get the full string of PHP’s getTraceAsString()?

User picture User · Dec 22, 2009 · Viewed 22.2k times · Source

I'm using getTraceAsString() to get a stack trace but the string is being truncated for some reason.

Example, an exception is thrown and I log the string using:

catch (SoapFault $e) {
error_log( $e->getTraceAsString() )
}

The string thats prints out is:

#0 C:\Somedirectory\Somedirectory\Somedirectory\Somedir\SomeScript.php(10): SoapClient->SoapClient('http://www.ex...')

How can I get the full string to print?

Answer

Steve picture Steve · May 20, 2011

I created this function to return a stack trace with no truncated strings:

function getExceptionTraceAsString($exception) {
    $rtn = "";
    $count = 0;
    foreach ($exception->getTrace() as $frame) {
        $args = "";
        if (isset($frame['args'])) {
            $args = array();
            foreach ($frame['args'] as $arg) {
                if (is_string($arg)) {
                    $args[] = "'" . $arg . "'";
                } elseif (is_array($arg)) {
                    $args[] = "Array";
                } elseif (is_null($arg)) {
                    $args[] = 'NULL';
                } elseif (is_bool($arg)) {
                    $args[] = ($arg) ? "true" : "false";
                } elseif (is_object($arg)) {
                    $args[] = get_class($arg);
                } elseif (is_resource($arg)) {
                    $args[] = get_resource_type($arg);
                } else {
                    $args[] = $arg;
                }   
            }   
            $args = join(", ", $args);
        }
        $rtn .= sprintf(
            "#%s %s(%s): %s%s%s(%s)\n",
            $count,
            $frame['file'],
            $frame['line'],
            isset($frame['class']) ? $frame['class'] : '',
            isset($frame['type']) ? $frame['type'] : '', // "->" or "::"
            $frame['function'],
            $args
        );
        $count++;
    }
    return $rtn;
}

Alternatively, you could edit the php source where it is truncating the output: https://github.com/php/php-src/blob/master/Zend/zend_exceptions.c#L392