Skip to content

Instantly share code, notes, and snippets.

@lsloan
Last active August 29, 2015 14:25
Show Gist options
  • Save lsloan/073e212b60aa4ff13b01 to your computer and use it in GitHub Desktop.
Save lsloan/073e212b60aa4ff13b01 to your computer and use it in GitHub Desktop.
A one-line solution to send an edited stack trace to the error log.
<?php
// Print stack trace, removing repeated absolute path on each file
error_log(str_replace($_SERVER['DOCUMENT_ROOT'], '', (new Exception())->getTraceAsString()));
@lsloan
Copy link
Author

lsloan commented Jul 16, 2015

PHP offers a couple of different ways to get a stack backtrace, but each has some drawbacks:

  • debug_backtrace(): Produces a tree of associative arrays that is detailed, but would take some additional coding to put it into an easily readable format. Using var_dump() on the arrays would work, but makes the output very long.
  • debug_print_backtrace(): Produces a nicely formatted backtrace, but immediately sends it to the output. To get the string for formatting or sending to a log would require turning output buffering on and off again. Also, the backtrace from this function may be missing some information about the files containing the functions listed in the stack.

The alternative shown here instantiates an exception just to get the stack trace as a string. That's all that's needed. The code goes on to shorten each line by removing the repeated absolute paths to each file. (This assumes most of the files are within the document root that contains the application.) Finally, it's sent to the error log rather than cluttering up the output.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment