1

I just handcrafted a complex order process which will go online soon. For the first time, I want to be informed about any errors that occur, but I also want them to be logged. This answer suggests to first log them and then mail them to be more secure since mailing might fail. But when I catch the exception, it's not being logged, and when I don't catch it, I can't send an email.

My code:

// convert errors to exceptions
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");

try {
    // ... some code that might cause errors or throw exceptions
} catch(Exception $e) {
    log(...); // how can i make the error being logged here?
    mail(...); // afterwards i send an email
    throw $e; // i could re-throw it this way, but only after mailing it, cause it kills the process.
}

Sure, I could write my one logging routine, but I guess PHP already does it in a clever way which I'd like to use.

Another thing that would be great is having some control that makes sure that no more then x error emails per hour are sent out.

All in all it seems to be a pretty common setup, but I couldn't find a ready solution. Or is the idea somehow stupid in the hole?

0

1 Answer 1

1

The function error_log() will automatically log your message to the web server's error_log file. If you prefer, you can specify a custom log file vs. the default error_log file.

So you can log a simple error message in error_log like this:

error_log("This is my error message");

Or to log an exception message in /var/log/web_error_log:

} catch (Exception $e) {
    error_log($e->getMessage(), 3, '/var/log/web_error_log');
}

See https://www.php.net/manual/en/function.error-log.php for more details on error_log.

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

Comments

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.