Are you a developer looking to automate PHP error logging?
PHP error logging is a system that captures runtime issues within PHP code, recording details about errors and warnings. This tool is invaluable for developers, as it provides insights into why and where a program may be failing, which is crucial for troubleshooting, performance optimization, and improving user experience.
This guide focuses on different types of PHP errors, how to enable PHP error logging, how to view logs, how to automate error logging, and much more.
Let’s get started…
Understanding Different Types of PHP Errors
PHP errors occur when something is off-base within the code. They can be as complex as calling an incorrect variable or as simple as missing a semicolon. You must understand the kind of errors you face to solve them effectively. So, let’s find out more about common PHP errors.
Warning Error
PHP warning errors alert about a problem that may cause a more critical error in the long run. Warning errors do not break down the code execution and commonly occur when using a file path that doesn’t exist.
For example, if the error below pops up, you must check the file name in the code or directory, as the script may not find it due to the syntax error.
<?php echo "Warning error"'; include ("external_file.php"); ? >
There is no file named “external_file,” so the output will display an error message box, and the execution will not break down.
Notice Error
Notice errors are minor, and like warning errors, they don’t halt code execution. However, they can make it harder for the system to determine if there’s a real issue or just standard code behavior. Notice errors usually occur when the script tries to access an undefined variable.
Notice: [8] Undefined variable: undefinedVariable in /path/to/your/script.php on line 12
Syntax Error
Parsed, misused, or missing symbols often cause syntax errors. When the compiler detects an error, it terminates the script.
Parse/syntax errors are caused by:
- Unclosed brackets or quotes
- Missing or extra semicolons or parentheses
- Misspellings
Here’s an example of a parse error message:
PHP Parse error: syntax error, unexpected ‘5’ (L_NAME), expecting ‘)’ in /home/u802426761/domains/username/public_html/wp-config.php on line 32
Fatal Error
A fatal error happens when the code calls the function, but the function itself isn’t characterized. Unlike other PHP errors, a fatal error breaks down the execution and sometimes crashes the application as well.
There are three types of fatal errors:
- A startup fatal error happens when the framework can’t run the code due to a mistake during installation.
- A compile-time fatal error occurs when the developer uses an undefined function, class, or non-existent variable or data.
- A runtime fatal error is similar to a compile-time fatal error but happens during the program execution.
Here’s an example of a PHP fatal error:
PHP Fatal error: Call to undefined function get_header() in /var/www/username/public/blog/wp-content/themes/theme/index.php on line 37
Another reason for a fatal error is exceeding the execution time:
Fatal error: Maximum execution time of 30 seconds exceeded in /home/username/domains/domain.com/public_html/wp-includes/class-phpmailer.php on line 737
Configuration Basics for PHP Error Logging
PHP error logging configuration settings allow developers to manage how errors are recorded and displayed. Key directives like log_errors and error_log enable or disable error logging and specify custom file paths for storing log files.
Let’s start by reviewing some configuration directives and default file locations to understand the flow of error handling in PHP, including where logs are stored and how error visibility is controlled for development or production environments.
Configuration Directives
Configuration directives in PHP are settings in the php.ini file that control the behavior of the PHP runtime.
These directives allow developers to configure various aspects, such as error reporting, memory usage, and file upload limits, to optimize PHP’s functionality for their applications.
Directive | Default Value | Description |
memory_limit | 128M | Sets the maximum amount of memory a script can consume. Prevents scripts from exhausting server memory. |
max_execution_time | 30 | Sets the maximum time (in seconds) a script is allowed to run before being terminated. |
display_errors | Off | Controls whether errors are displayed as part of the output. Used during development, not recommended in production. |
error_reporting | E_ALL | Defines the level of error reporting (e.g., warnings, notices). |
post_max_size | 8M | Sets the max size of POST data allowed. Should be higher than upload_max_filesize. |
upload_max_filesize | 2M | Specifies the max size for uploaded files. Useful for controlling upload limits. |
log_errors | On | Enables or disables error logging. Helps capture errors in logs rather than displaying them to users. |
date.timezone | Not set | Specifies the default timezone used by all date/time functions. Must be set to avoid warnings. |
session.gc_maxlifetime | 1440 | Defines the max time in seconds for which session data is kept. |
realpath_cache_size | 4M | Sets the size of the realpath cache. Improves performance when many file operations are performed. |
For detailed information on these directives and more, check out the PHP documentation on configuration directives and the description of core php.ini settings.
File Locations
PHP error logs are set up in the php.ini file, where you can define a custom path for error_log. If this file location isn’t configured, PHP defaults to sending error logs to the system log or stderr() in CLI contexts.
Here are the default configuration locations for PHP error logs, which vary by OS and PHP environment:
Operating System | Default Path for Error Log | Additional Notes |
Linux | /var/log/syslog
/var/log/messages |
Default location if error_log isn’t set in php.ini. Logs may also be directed to web server logs (e.g., /var/log/apache2/error.log for Apache). |
Windows | Windows Event Viewer
(Application Logs) |
Errors appear in the Event Viewer under “Application Logs”. Custom paths can be set via php.ini. |
macOS | /var/log/system.log | Logs are directed here by default if not otherwise specified in php.ini. |
Custom | User-defined path in php.ini | Specified using the error_log directive. For example, error_log = /path/to/php_errors.log. |
How to Enable PHP Error Logging [7 Methods]
Enabling PHP error logging can be done through various methods. Below are seven effective techniques for enabling PHP error logging.
Method 1: Monitor Error Log Using Cloudways Platform [Easiest Method]
Since enabling PHP error logging requires modification in the php.ini file, you can simply activate the error logging from the Cloudways platform itself with simple clicks. You can easily customize error_reporting and logging settings from your Cloudways Platform.
- Log in to your Cloudways dashboard and click the “Servers” tab.
- Once it’s enabled, your PHP error logs will be recorded in your applications’ “Logs” folder. You can also check the errors under each application monitoring tab.
- You can easily filter the php errors and warnings from the logs filter.
Method 2: Enable Error Log Using cPanel
If your hosting provider uses cPanel, you can enable PHP error logging through the cPanel interface:
- Log in to your cPanel dashboard and navigate to the “Software” section.
- Click on the “Select PHP Version” option.
- Scroll down to the “PHP INI Editor” section and click “Open in New Window.”
- Locate the “error_log” directive and set its value to the desired log file path.
Method 3: Enable Error Log Using the .htaccess File
You can also enable PHP error logging by modifying the .htaccess file in your website’s root directory. Add the following lines:
php_flag display_startup_errors on php_flag display_errors on php_flag html_errors on php_value error_reporting 32767
Method 4: Enable Error Log Using php.ini File
If you have access to the php.ini file, you can enable PHP error logging by modifying the following directives:
display_errors = On error_reporting = E_ALL log_errors = On error_log = /path/to/error_log
Method 5: Enable PHP Error Logging to a File Using the error_log() Function
You can use the error_log() function in your PHP code to log custom messages to the error log:
error_log('This is a custom error message');
Method 6: Enable Automatic Collection of PHP Errors with Retrace APM
To enable the automatic collection of PHP errors with Retrace APM, first sign up for a Retrace account and install the Retrace agent on your server, ensuring that APM monitoring is enabled during installation.
Once set up, Retrace will automatically collect errors, warnings, and notices from your PHP application without requiring additional code changes.
You can view the collected errors in your Retrace account’s “Errors” section, which provides detailed information, including error messages, stack traces, and affected files.
Additionally, Retrace integrates with popular issue-tracking tools and collects performance metrics, streamlining your error monitoring and troubleshooting process for improved application health and efficiency.
Method 7: Enable PHP Error Logging Through the Web Server Configuration
Depending on your web server configuration, you can enable PHP error logging through server settings. For example, you can add these directives to the httpd.conf file in Apache:
PHP_value error_log /path/to/error_log
File Locations
The location of the PHP error log file is defined by the error_log directive in php.ini. However, you can choose a path that best suits your environment.
Here are a few common file paths:
- /var/log/php_errors.log: Often used on Unix-based systems.
- /tmp/php-error.log: A temporary location suitable for testing.
- /path/to/project/php-error.log: A custom location within your project directory, which may help with file access.
To set a custom path, use the following directive in php.ini or in the script:
How to View PHP Error Logs
Now that you know how to enable PHP error logs, let’s examine different ways to view them.
Method 1: Using the .htaccess File
The .htaccess file, typically used in Apache servers, can be configured to enable PHP error logging for specific directories.
Navigate to Your Laravel Project’s Root Directory, In your project folder, find the public directory my-laravel-app/public/. The .htaccess file should be located directly inside the public folder
Add the following lines to your .htaccess file:
php_flag log_errors On php_value error_log /path/to/php-error.log
Replace /path/to/php-error.log with the actual path where you want to store the error log file. After adding this code, PHP errors for that directory will be logged to the specified file.
Method 2: Using php.ini File
Configuring PHP error logging involves a few primary settings in the php.ini file, where you can control error visibility and logging.
- First, locate your php.ini file;
- Open your code editor to create a .php file. In this case, add this piece of code to the new file:
<?php phpinfo(); ?>
- Open the local Disk. Locate the Wamp folder, then open the www folder. Copy this info.php file to the wamp/www folder.
- Open the browser. Type localhost/info.php in the address bar. You will see a table of available settings.
- Try to search with php.ini as the keyword. In the Loaded Configuration File field, you will see the path to the php.ini file. In this case, it’s C:\wamp\bin\apache\apache2.4.9\bin\php.ini. Just follow the path to find the file:
- Here is the php.ini file that you need to edit. Just open and edit the file, then save it:
To log errors in PHP,
- Open the php.ini file.
- Find and update the following settings:
error_reporting = E_ALL & ~E_NOTICE error_reporting = E_ALL & ~E_NOTICE | E_STRICT error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ER… _ERROR error_reporting = E_ALL & ~E_NOTICE
- If you want to enable PHP error logging in individual files, add this code at the top of the PHP file.
ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
- You must enable only one statement to parse the log errors in the php.ini file:
display_errors = on.
- Now, you can easily see logged errors in your browser.
- Some of the additional commands you can write for PHP error logging include:
display_errors = Off ; Hides errors from being displayed on the front end log_errors = On ; Enables error logging error_log = /path/to/php-error.log ; Specifies the error log file location error_reporting = E_ALL ; Logs all types of errors
- Save the file and restart your web server for the changes to take effect.
Method 3: Viewing Logs on the Server
If you have server access, you can directly view the PHP error log file. The location of this file depends on your server configuration. Common file paths include:
- /var/log/php_errors.log on Unix-based systems
- /usr/local/apache/logs/error_log on some configurations
Use SSH to access your server and view the logs. You can use commands like cat, tail, or less to read the logs:
# To see last 50 lines of the PHP error log run the following line of code tail -n 50 /var/log/php_errors.log
Method 4: Using Logging Functions
PHP also offers built-in functions to log errors manually, allowing you to create custom error messages in the error log file.
1. error_log() function
The error_log() function can be used in your PHP scripts to log specific events or errors.
Here’s an example:
error_log("Custom error message: Something went wrong!", 3, "/path/to/php-error.log");
- Custom error message: Something went wrong! is the error message.
- 3 specifies that the message should be appended to the error log file.
- “/path/to/php-error.log” is the path to the log file
Using error_log() is useful for logging errors conditionally, especially in scripts where custom error messages are needed for troubleshooting.
2. trigger_error() Function
trigger_error() generates a user-level error, warning, or notice.
This function is helpful in cases where you want to stop execution or display warnings based on specific conditions.
<?php // Generates a user-level warning trigger_error("This is a custom warning", E_USER_WARNING); // Generates a user-level error (fatal) trigger_error("Fatal error encountered", E_USER_ERROR); ?>
3. syslog() Function
Another type of log function is syslog(). Its basic purpose is to log messages to the system logger, which is managed by the OS.
Syslog () logs messages directly to the operating system’s logging system. This function is useful in environments where system-level logging is preferred, and log management is centralized.
<?php // Open a connection to the system logger openlog("php_script", LOG_PID | LOG_PERROR, LOG_LOCAL0); // Logs an informational message to the system log syslog(LOG_INFO, "This is an informational message"); // Logs an error message to the system log syslog(LOG_ERR, "This is an error message"); // Close the connection to the system logger closelog(); ?>
Advanced Customization of PHP Error Logging
Advanced customization of PHP error logging involves tailoring how errors are recorded and managed in your application, particularly in production environments.
This can enhance debugging, provide clearer insights, and optimize application performance by structuring logs and suppressing non-critical errors.
To show how to run advanced customization of PHP error logging, I will set up a structured error logging system in PHP using the Monolog library, configuring it to log errors in JSON format to a file for easier parsing and analysis.
We will also use PHP configurations to suppress non-critical errors in production, directing only essential errors to a log file while hiding them from end users for improved security and user experience.
Custom Log Formats: Using JSON or Other Structured Formats
Using structured formats for logging, such as JSON, makes logs machine-readable. JSON logging is especially beneficial in complex applications.
This allows logs to be easily parsed, searched, and analyzed by various tools and logging systems, enabling better insights in production environments.
Configuring JSON Log Format in PHP
- First, install Monolog using Composer.
composer require monolog/monolog
PHP error logs are in plain text format, you can customize the log format to JSON by using a third-party logging library tool such as Monolog,
- Then, create a simple logger that outputs errors in JSON format.
<?php use Monolog\Logger; use Monolog\Handler\StreamHandler; use Monolog\Formatter\JsonFormatter; // Create the logger $logger = new Logger('custom_logger'); // Create a StreamHandler to write logs to a file $handler = new StreamHandler(__DIR__ . '/logs/app.log', Logger::ERROR); // Set the handler's formatter to JSON $handler->setFormatter(new JsonFormatter()); // Push the handler to the logger $logger->pushHandler($handler); // Log an error with a custom message and context $logger->error('An unexpected error occurred', [ 'user_id' => 1234, 'action' => 'update_profile', 'timestamp' => date('Y-m-d H:i:s') ]);
Suppressing Errors: Techniques for Hiding Non-Critical Errors in Production
In production environments, it’s generally best practice to hide non-critical or sensitive errors from end users and instead log them for developers to review later.
Suppressing these errors improves user experience, reduces potential security risks, and keeps the application running smoothly even when minor issues arise.
PHP provides configuration options to control which errors are reported and whether they should be displayed to users.
- Disable Displaying Errors: This prevents errors from being shown on the screen. In php.ini, set:
display_errors = Off
- Configure Error Reporting Levels: Set error reporting to capture only critical errors while suppressing warnings or notices.
// Suppress non-critical errors error_reporting(E_ERROR | E_PARSE); // Only log critical errors
- Direct Error Output to a Log File: This option logs errors to a file instead of showing them, allowing developers to review them later.
log_errors = On error_log = /path/to/error.log
Error Handling in PHP 8.x
PHP 8 has introduced new error-handling features and exceptions, including more detailed error messages and a refined set of exception types.
- TypeError and ValueError: These exceptions are stricter in PHP 8.x, especially with the introduction of new type handling and stricter typing rules. For example, TypeError will be thrown if you pass an argument with the wrong type.
- New Error Types: PHP 8 introduced ValueError, which is thrown when a function receives an argument that is correct in type but invalid in value.
- Enhanced ErrorException Handling: PHP 8 offers better integration with ErrorException, allowing developers to catch and convert errors to exceptions more efficiently.
<?php function divide($dividend, $divisor) { if ($divisor == 0) { throw new Exception("Cannot divide by zero."); } return $dividend / $divisor; } try { echo divide(10, 0); } catch (Exception $e) { echo "Error: " . $e->getMessage(); }
Error: Cannot divide by zero.
Using Custom Exceptions
PHP 8.x allows you to define custom exceptions by extending the Exception class, enabling more specific error handling.
<?php function inverse($x) { if (!$x) { throw new Exception('Division by zero.'); } return 1/$x; } try { echo inverse(5) . "\n"; echo inverse(0) . "\n"; } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Continue execution echo "Hello World\n"; ?>
Output
Exception Handling With a Finally Block
The finally block is used for cleanup actions, such as closing files or releasing resources, ensuring they occur even if an error happens during execution.
<?php function inverse($x) { if (!$x) { throw new Exception('Division by zero.'); } return 1/$x; } try { echo inverse(5) . "\n"; } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } finally { echo "First finally.\n"; } try { echo inverse(0) . "\n"; } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } finally { echo "Second finally.\n"; } // Continue execution echo "Hello World\n"; ?>
Output
Automating PHP Error Logging Process
Automating the error logging process in PHP is an effective way to handle errors consistently and reduce the risk of unhandled errors.
- Create a custom error handler function that captures and logs errors.
- This handler can format and direct logs to a file or logging service.
<?php // config.php or index.php // Define the error logging function function logError($severity, $message, $file, $line) { $logMessage = json_encode([ 'severity' => $severity, 'message' => $message, 'file' => $file, 'line' => $line, 'timestamp' => date('Y-m-d H:i:s') ]); // Log to a specific file error_log($logMessage . PHP_EOL, 3, __DIR__ . '/logs/errors.log'); }
- Next, Use set_error_handler() to convert traditional PHP errors into exceptions, making it easier to handle all errors in one place.
// Set a custom error handler to convert errors to exceptions set_error_handler(function ($severity, $message, $file, $line) { // Only log specific error levels if needed if (!(error_reporting() & $severity)) { return; } throw new ErrorException($message, 0, $severity, $file, $line); });
- Now you need to set a custom exception handler.
set_exception_handler(function ($exception) { logError( $exception->getCode(), $exception->getMessage(), $exception->getFile(), $exception->getLine() ); });
- Use register_shutdown_function() for Fatal Errors.
register_shutdown_function(function () { $error = error_get_last(); if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) { logError($error['type'], $error['message'], $error['file'], $error['line']); } });
Output Error
After executing this setup, logs/errors.log might contain entries like:
In the following output,
1. Log 1: This log entry indicates a non-fatal PHP warning due to an undefined variable on line 35 of index.php.
The first log entry is of Severity 2 and reports an “Undefined variable: undefinedVariable.” The error occurred in the /path/to/index.php file.
2. Log 2: This entry serves as a low-severity informational log, likely used to test the exception logging functionality.
The second log entry is of Severity 1 and records a “Test exception logging” message. This error was logged in the same file, /path/to/index.php, on line 37.
Host PHP Websites with Ease [Starts at $11 Credit]
- Free Staging
- Free backup
- PHP 8.0
- Unlimited Websites
Final Words
PHP error log helps you troubleshoot problems on a website by logging the error details, including the PHP file and code line that needs fixation.
This article has demonstrated how logging errors in PHP are configured in the php.ini file. Further, it discusses the right way to log errors and how to enable and automate PHP error logging, keeping the dev work on track.
If you find this article helpful and want to share your views about the topic, feel free to write down your suggestions in the comments below.
Q: How do you enable PHP error logging?
A) To enable PHP error logging, set log_errors = On in your php.ini file. You also need to specify a file path for error_log where the errors will be recorded. This ensures that PHP errors are logged to the specified file instead of being displayed on the screen.
Q: How do I enable debug logging in PHP?
A) To enable debug logging, first make sure log_errors = On is set in your php.ini file. Then, use error_reporting(E_ALL) in your PHP script to capture all types of errors, including warnings and notices. This allows detailed debugging information to be logged.
Q: How do I enable PHP error display?
A) To display errors directly on the web page, set display_errors = On in your php.ini file. Additionally, use error_reporting(E_ALL) in your PHP code to display all types of errors, including notices, warnings, and fatal errors during development.
Q: How to generate an error log in PHP?
A) To generate an error log in PHP, ensure that log_errors is enabled and specify the path to your log file using the error_log directive in php.ini. You can also use error_reporting(E_ALL) to capture all errors and send them to the log file for troubleshooting.
Inshal Ali
Inshal is a Content Marketer at Cloudways. With background in computer science, skill of content and a whole lot of creativity, he helps business reach the sky and go beyond through content that speaks the language of their customers. Apart from work, you will see him mostly in some online games or on a football field.