phip1611
phip1611

Reputation: 6140

debug_print_backtrace() to String for log-file

I have a problem. I would like to log the backtrace in a specific case in a log-file. debug_print_backtrace() builds a correct string for my purposes but debug_print_backtrace() prints the trace on the screen instead of returning it.

Upvotes: 24

Views: 14423

Answers (4)

cstutorial
cstutorial

Reputation: 11

echo "<table><th>File</th><th>Line</th>";
    foreach(debug_backtrace() as $error){
        echo "<tr><td>".$error['file']."</td>";
        echo "<td>".$error['line']."</td>";
        echo "</tr>";
    }
    echo "</table>"; die;

Upvotes: 0

HoldOffHunger
HoldOffHunger

Reputation: 20881

It's possible to do it with even less code, actually. Avoid the overhead of buffering with...

$error_string = (new Exception)->getTraceAsString();

That gives you the exact same output as debug_print_backtrace() stored to the $error_string variable.

And if you want to get more information for a more valuable stacktrace (line numbers, local object vars, etc.), try...

$error_string = print_r($e->getTrace(), true);

Upvotes: 20

Sudheesh.M.S
Sudheesh.M.S

Reputation: 508

To add on to the answer given by @HoldOffHunger, the following would have been sufficient for logging purpose:

$this->log(print_r(debug_backtrace(), true));

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

Use another function. debug_backtrace() returns an array that you can loop through, format and save:

$data = debug_backtrace();

Or use output buffering for the formatted output string:

ob_start();
debug_print_backtrace();
$data = ob_get_clean();

Upvotes: 30

Related Questions