0

I want to use a custom exception handler (set with set_exception_handler() function) to control what is printed to a user when unhandled exception occurs.

Unfortunately, in this case exception is not logged to a php error log and I don't want to write my own logging code because automatic exception logging was absolutely ok for me.

The question is:
Is there a way to make PHP log exception (as by default) if custom exception handler was executed? If no, is there a way to log into main php error log file?

1

1 Answer 1

2

Is there a way to make PHP log exception (as by default) if custom exception handler was executed?

No, not from what PHP offers (e.g. return FALSE in the callback).

If no, is there a way to log into main php error log file?

Yes, you can use the error_logDocs function for that. The ExceptionDocs should contain the message as well as code, file name and line number.

It also is stringable and error_log() adds the delimiting newline character, so it directly works in logging (it will even downsize based on log_errors_max_len configured size):

set_exception_handler(function ($throwable) {
    error_log((string)$throwable);
});

Or less verbose:

set_exception_handler('error_log');

Demo/Playground: https://3v4l.org/s41Vn


Another more or less dirty trick is to create an exception capturing object that remains in memory all the time. If it captures an uncatched exception, it will handle it and store it. In case of destruction (at the end of the process) it can re-throw it. Then PHP needs to deal with it and probably logs it. However I would consider that experimental and also perhaps short-sighted as there can be only one exception handler and it catches uncaught ones, so there is not much way to continue (more shutdown function material perhaps).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanx, I will use the error_log() function. Actually, clentfort gave a link to the example where error_log() is used, but based on the comment there I've decided that it's some user function :)
yeah the PHP manual very often has some gems burried, so worth to scan and to review the user comments. You often find there better information than here on SO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.