Php – How to log uncaught exceptions in PHP

error handlingerror-loggingexceptionPHP

I've found out how to convert errors into exceptions, and I display them nicely if they aren't caught, but I don't know how to log them in a useful way. Simply writing them to a file won't be useful, will it? And would you risk accessing a database, when you don't know what caused the exception yet?

Best Answer

You could use set_error_handler to set a custom exception to log your errors. I'd personally consider storing them in the database as the default Exception handler's backtrace can provide information on what caused it - this of course won't be possible if the database handler triggered the exception however.

You could also use error_log to log your errors. It has a choice of message destinations including:

Quoted from error_log

  1. PHP's system logger, using the Operating System's system logging mechanism or a file, depending on what the error_log configuration directive is set to. This is the default option.
  2. Sent by email to the address in the destination parameter. This is the only message type where the fourth parameter, extra_headers is used.
  3. Appended to the file destination . A newline is not automatically added to the end of the message string.

Edit: Does markdown have a noparse tag for underscores?