Leo Jiang
Leo Jiang

Reputation: 26085

How can I save a PHP backtrace to the error log?

I'm using this right now:

error_log(serialize(debug_backtrace()));

But I have to unserialize it every time. Is there a better way to store backtraces?

Upvotes: 51

Views: 51717

Answers (6)

Nicolas Bouvrette
Nicolas Bouvrette

Reputation: 4757

For those who might want a more compact version, this will also do the trick:

error_log((new Exception())->getTraceAsString())

Upvotes: 5

Robert Sinclair
Robert Sinclair

Reputation: 5416

The following can either be written to a .txt file or you can also access it's contents (like $content[0]) as opposed to var_export which is a bit trickier I find:

    $content = unserialize(serialize(debug_backtrace()));

Upvotes: 1

Álvaro González
Álvaro González

Reputation: 146450

This should generate a readable string:

error_log(print_r(debug_backtrace(), true));

Additionally, debug_print_backtrace() prints the back trace as string and its output can be captured with regular output buffer functions:

ob_start();
debug_print_backtrace();
error_log(ob_get_clean());

Upvotes: 67

Igor S
Igor S

Reputation: 1895

From my perspective the best approach is using an exception functionality:

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

Upvotes: 28

Pramendra Gupta
Pramendra Gupta

Reputation: 14873

    $log = var_export(debug_backtrace(), true);

Then use the variable $log to log in file or what ever.

Upvotes: 8

Kzqai
Kzqai

Reputation: 23062

A little ugly but workable, I do this:

 error_log('Identifying string so that it doesn\'t just end up as gibberish' . json_encode(debug_backtrace()));

Upvotes: 5

Related Questions