Pavel Niedoba
Pavel Niedoba

Reputation: 1557

PHP function to print stack trace arguments into log

I'm trying to collect debug information in my error handler function. I can analyze the stack and get the file and line number. I also have an array of arguments which I would like to print into my log as well but I don't want to bloat the log file.

I want to print all numbers, booleans, strings (for example the first 50 characters), class names for objects, size of arrays, null for nulls and whatever comes up later in a reasonable form. It should produce no new lines so I have one line per stack entry.

Since I don't want to reinvent the wheel, is there a function out of the box exist in PHP which will behave as described?

Upvotes: 4

Views: 2359

Answers (3)

Nadir Latif
Nadir Latif

Reputation: 3763

You can also use XDebug to generate a stack trace: https://xdebug.org/docs/stack_trace

Upvotes: 1

Pavel Niedoba
Pavel Niedoba

Reputation: 1557

First I tried to do it myself:

debug_backtrace(); 

gives array of which I processed using:

protected function backTraceLine(array $line)
{
    $ret = "";
    if (isset ($line['file']))
        $ret = $ret . $line['file'];
    if (isset ($line['function']))
        $ret = $ret . $line['function'];
    if (isset ($line['file']))
        $ret = "[" . $ret . $line['line'] . "]";
    try {
        $args = $line['args'];
        if (is_array($args))
            $ret = $ret . "(" . implode(",", $args) . ")";
    } catch (Exception $e) {
    }
    return $ret;
}

But later I found this method which does exactly what I need:

$exception->getTraceAsString()

If there's no Exception in place we can create new one and get stack from there

Upvotes: 1

Ray Hunter
Ray Hunter

Reputation: 15557

You can check if there are php packages or libs that do logging. For example, pear has some logging packages you can use under Logging.

Upvotes: 1

Related Questions