19

Is it possible to log stacktraces for php warnings? Or catch a warning and error_log() it?

There's some code causing warnings in my error log, but it's impossible to know what's causing these warnings without knowing the stack trace.

quano
  • 17,702
  • 24
  • 94
  • 108

4 Answers4

15

There is an example of using set_error_handler() in conjunction with ErrorException to do just this:

https://php.net/manual/en/class.errorexception.php

You would just need to implement your custom logging functionality inside of the handler function.


UPDATE:

Note, this also works for warnings, and many other error types. For full compatibility, see the manual for set_error_handler():

https://php.net/set_error_handler

faintsignal
  • 1,746
  • 3
  • 19
  • 28
AJ.
  • 25,364
  • 15
  • 77
  • 87
8

Just throw this at the start of your script:

set_error_handler(function($severity, $message, $file, $line) {
    if (error_reporting() & $severity) {
        throw new ErrorException($message, 0, $severity, $file, $line);
    }
});

Remove the if you want to log everything, even if it's suppressed.

mpen
  • 237,624
  • 230
  • 766
  • 1,119
1

I believe xdebug would go to log if that's how you have it enabled in your php.ini file, but it has stack tracing (with some bonus features like showing the local variables). It is not recommend for a production environment though.

XDebug Stack Traces

Paul DelRe
  • 3,845
  • 1
  • 21
  • 25
0

Here you go:

class WarningWithStacktrace extends ErrorException {}
set_error_handler(function($severity, $message, $file, $line) {
    if ((error_reporting() & $severity)) {
        if ($severity & (E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE)) {
            $ex = new WarningWithStacktrace($message, 0, $severity, $file, $line);
            echo "\n" . $ex . "\n\n";
            return true;
        } else {
            throw new ErrorException($message, 0, $severity, $file, $line);
        }
    }
});

Errors/exceptions are thrown as usual, notices/warnings are printed only.

PS: Strict and other warning levels are not addressed, modify the code if needed...

mvorisek
  • 2,758
  • 1
  • 12
  • 46