← Back to Chapters

PHP Exception Handling – Exception Logging

? PHP Exception Handling – Exception Logging

? Quick Overview

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.

? Key Concepts

  • Exceptions represent runtime problems in a program.
  • Logging stores exception details for later analysis.
  • Logs help debug issues without breaking user experience.
  • PHP supports manual and library-based logging.

? Syntax & Theory

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.

? Code Example

? View Code Example
// 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>";
}
?>

? Live Output / Explanation

? Output

When division by zero occurs, the user sees a friendly message, while the detailed error is saved inside exceptions.log with date and time.

? Interactive Concept

You can experiment by changing the divisor value below to see how the system handles success vs. logging an error.

10 /
VIRTUAL LOG FILE (exceptions.log)
System initialized... waiting for logs.

? Use Cases

  • Debugging production issues safely
  • Tracking recurring application errors
  • Monitoring failed operations
  • Auditing system behavior

? Tips & Best Practices

  • Always enable exception logging in production environments.
  • Avoid logging sensitive user data.
  • Use timestamps and context in log entries.
  • Consider libraries like Monolog for scalability.

? Try It Yourself

  • Add stack trace logging using $e->getTraceAsString().
  • Create separate log files for different exception types.
  • Send critical logs via email or external monitoring tools.