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

6

50

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?

Monomial answered 3/12, 2011 at 16:56 Comment(0)
P
66

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());
Pacifistic answered 3/12, 2011 at 17:4 Comment(2)
debug_backtrace() returns a big array, which doesn't print_r real well. The second method prints a nicer looking backtrace. Another method I sometimes use is just error_log(new Exception('message here, if you want')); because I like the way the backtrace is formatted for exceptions.Shew
@JayK - FWIW, sassman on a comment on Igor's answer says about Exception: "But it does not include the variables of the calling scope. The benefit of debug_print_backtrace() is it includes a copy of the runtime context."Bloat
E
28

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

$e = new Exception();
$e->getTraceAsString();
Eparch answered 9/11, 2016 at 13:16 Comment(3)
it prints the trace, yes. But it does not include the variables of the calling scope. The benefit of debug_print_backtrace() is it includes a copy of the runtime context.Keepsake
Or as a one-liner: (new \Exception())->getTraceAsString()Impresario
And in PHP 7+, slightly shorter: (new \Error)->getTraceAsString()Thorvaldsen
H
8
    $log = var_export(debug_backtrace(), true);

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

Homocercal answered 7/6, 2012 at 4:7 Comment(1)
var_export does not handle circular references. Therefore that solution is not safe to use.Keepsake
B
5

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

error_log((new Exception())->getTraceAsString())
Batey answered 18/7, 2020 at 14:47 Comment(0)
T
4

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()));
Transitory answered 3/12, 2011 at 17:1 Comment(0)
E
1

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()));
Epigeous answered 17/4, 2019 at 5:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.