← Back to PHP Course | Chapter 13: Error Handling | Lesson 4 of 5

PHP Error Logging

Introduction to Error Logging

Showing raw errors to visitors leaks implementation details and looks unprofessional; error_log() writes error messages to the server's log file instead, where developers can review them without exposing anything to users.

Example: Introduction to Error Logging

php
<?php
error_log("A test error message from the application");
echo "Error written to the server log, not shown to visitors";
?>

Logging to Custom Files

Passing 3 as the message type to error_log(), along with a file path, redirects that specific message into your own custom log file rather than PHP's default system log, which helps keep application logs organized.

Example: Logging to Custom Files

php
<?php
error_log("Custom log entry" . PHP_EOL, 3, "app_errors.log");
echo file_get_contents("app_errors.log");
?>

Logging inside Error Handlers

Combining a custom error handler with error_log() means every PHP-level error gets written to a log automatically, without needing to add logging calls throughout your codebase by hand.

Example: Logging inside Error Handlers

php
<?php
set_error_handler(function ($errno, $errstr) {
    error_log("Handled error: $errstr");
    echo "Logged automatically";
});
echo $undefinedVar;
?>

Exception Logging

Wrapping risky code in try-catch and logging the exception's message and stack trace keeps users away from scary technical detail while still giving you everything you need to diagnose the failure later.

Example: Exception Logging

php
<?php
try {
    throw new Exception("Payment failed");
} catch (Exception $e) {
    error_log($e->getMessage() . "\n" . $e->getTraceAsString());
    echo "Something went wrong. Please try again.";
}
?>

Log File Management

Log files that grow unchecked slow down searches and can fill up disk space; periodically checking file size (or rotating logs on a schedule) keeps debugging fast and prevents storage issues.

Example: Log File Management

php
<?php
file_put_contents("app_errors.log", "Sample log line\n", FILE_APPEND);
$size = filesize("app_errors.log");
echo "Log file size: $size bytes";
?>
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.