Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Log stacktrace for warnings?

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.

like image 417
quano Avatar asked Jun 21 '11 14:06

quano


People also ask

Should Stacktrace be logged?

Therefore, you should log a stacktrace if, and only if, and always if, the exception indicates a bug in the program. However, that does not always indicate that a method you write should catch and log the exception.

What is error Stacktrace?

Stack trace error is a generic term frequently associated with long error messages. The stack trace information identifies where in the program the error occurs and is helpful to programmers. For users, the long stack track information may not be very useful for troubleshooting web errors.

What is stack trace error in php?

But, what is a stack trace? In essence, it is a rundown of every file and function that is called leading up to the error. To be clear, a stack trace doesn't include the files and functions that are touched before the error occurred, only the chain of methods that are called as the error happened.


2 Answers

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

like image 136
AJ. Avatar answered Oct 15 '22 15:10

AJ.


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.

like image 43
mpen Avatar answered Oct 15 '22 15:10

mpen