Exception logging in PHP allows developers to record runtime errors and exceptional conditions into log files instead of exposing sensitive details to users. This technique is essential for debugging, monitoring, and maintaining production applications.
In PHP, exceptions are handled using try, catch, and throw. When an exception occurs, it can be written to a file using functions like file_put_contents() or error_log(). Logging libraries such as Monolog offer advanced capabilities.
// Function that logs exceptions to a file
<?php
function divide($a, $b) {
if ($b == 0) {
throw new Exception("Division by zero attempted: $a / $b");
}
return $a / $b;
}
try {
$result = divide(10, 0);
echo "Result: $result<br>";
} catch (Exception $e) {
// Log exception with timestamp
$file = 'exceptions.log';
$message = date("Y-m-d H:i:s") . " - " . $e->getMessage() . "\n";
// Append the error message to the log file
file_put_contents($file, $message, FILE_APPEND);
echo "An error occurred. Check log file for details.<br>";
}
?>
When division by zero occurs, the user sees a friendly message, while the detailed error is saved inside exceptions.log with date and time.
You can experiment by changing the divisor value below to see how the system handles success vs. logging an error.
$e->getTraceAsString().