debug_print_backtrace() to String for log-file

橙三吉。 提交于 2020-12-29 05:11:02

问题


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.


回答1:


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();



回答2:


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.

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);



回答3:


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));


来源:https://stackoverflow.com/questions/19644447/debug-print-backtrace-to-string-for-log-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!