Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 950
Leo Jiang Avatar asked Dec 03 '11 16:12

Leo Jiang


People also ask

How do I get PHP to produce a Backtrace upon error?

For more advanced solution, you can use XDebug extension for PHP. By default when XDebug is loaded, it should show you automatically the backtrace in case of any fatal error. Or you trace into file (xdebug. auto_trace) to have a very big backtrace of the whole request or do the profiling (xdebug.

What is a PHP backtrace?

Definition and Usage. The debug_backtrace() function generates a PHP backtrace. This function displays data from the code that led up to the debug_backtrace() function. Returns an array of associative arrays.

What is PHP stack trace?

But, what is a stack trace? In essence, it is a rundown of every file and function that is called leading up to the error. To be clear, a stack trace doesn't include the files and functions that are touched before the error occurred, only the chain of methods that are called as the error happened.


2 Answers

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()); 
like image 143
Álvaro González Avatar answered Sep 24 '22 21:09

Álvaro González


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

$e = new Exception(); $e->getTraceAsString(); 
like image 36
Igor Sydorenko Avatar answered Sep 26 '22 21:09

Igor Sydorenko