PHP Error Logging
In this page:
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
error_log("A test error message from the application");
echo "Error written to the server log, not shown to visitors";
?>
Login to try C/C++/Java/PHP code in the editor
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
error_log("Custom log entry" . PHP_EOL, 3, "app_errors.log");
echo file_get_contents("app_errors.log");
?>
Login to try C/C++/Java/PHP code in the editor
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
set_error_handler(function ($errno, $errstr) {
error_log("Handled error: $errstr");
echo "Logged automatically";
});
echo $undefinedVar;
?>
Login to try C/C++/Java/PHP code in the editor
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
try {
throw new Exception("Payment failed");
} catch (Exception $e) {
error_log($e->getMessage() . "\n" . $e->getTraceAsString());
echo "Something went wrong. Please try again.";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
file_put_contents("app_errors.log", "Sample log line\n", FILE_APPEND);
$size = filesize("app_errors.log");
echo "Log file size: $size bytes";
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: