Error Handling and Logging
Relevant source files
The following files were used as context for generating this wiki page:
Introduction
CodeIgniter 4 provides a robust and flexible system for error handling and logging. The framework is designed to display comprehensive error details during development to aid in debugging, while gracefully hiding them and logging them in production environments to ensure security and a smooth user experience. This system is built around standard PHP interfaces, including PHP's Throwable interface and the PSR-3 LoggerInterface, making it both powerful and familiar to developers.
The error handling mechanism automatically catches uncaught exceptions and PHP errors, displaying them through a specialized Exceptions class. The logging system is highly configurable, allowing developers to set logging thresholds, customize log formats, and direct logs to various handlers, such as files. Both systems are configured through dedicated files in the app/Config directory, allowing for easy customization on a per-application basis.
Sources: source/general/errors.rst, source/general/logging.rst
Error Handling
CodeIgniter's error handling is managed by the CodeIgniter\Debug\Exceptions class. This class is the default exception handler for the framework and is responsible for processing all uncaught Throwable objects. Its behavior is primarily dictated by the CI_ENVIRONMENT constant.
Sources: source/libraries/exceptions.rst
Environment-Based Behavior
The framework's response to an error depends on the current environment:
- Development: In the
developmentenvironment, a detailed error report is displayed. This report includes the error message, the file and line number where it occurred, and a full stack trace, providing developers with all the necessary information to debug the issue. - Production: In the
productionenvironment, most error details are suppressed from the user. A generic error page is shown to the user (by default,app/Views/errors/html/production.php), and the full error details are written to the log files, based on the configured logging threshold.
This flow ensures that developers get the information they need while protecting sensitive application data from being exposed in a live environment.
The diagram below illustrates the decision flow of the exception handler.
Custom Exceptions
CodeIgniter provides several built-in exception types to handle common scenarios. Throwing these specific exceptions can trigger predefined responses, such as a "404 Not Found" page.
| Exception | Description |
|---|---|
PageNotFoundException | Thrown when a requested resource (like a controller or method) cannot be found. Results in a 404 page. |
ConfigException | Used for errors related to application configuration. |
DatabaseException | Thrown for database-related errors, such as a failed connection or a syntax error in a query. |
RedirectException | A special exception used internally to trigger a client-side redirect. |
Using PageNotFoundException is the standard way to generate a 404 response within a controller.
if (! $page = $model->find($id)) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
}
Sources: source/general/errors.rst, source/libraries/exceptions.rst
Configuration
While the core behavior is automatic, you can customize the exception handler via app/Config/Exceptions.php. This file allows you to configure which exceptions should be logged, which HTTP status codes they should return, and even replace the core exception handler with your own implementation.
Sources: source/libraries/exceptions.rst
Logging
CodeIgniter includes a logging feature that is compliant with the PSR-3 standard. This allows for standardized logging practices and interoperability with other PSR-3 compatible libraries. The primary interface for logging is the log_message() helper function or the Logger service.
Sources: source/general/logging.rst
Configuration
All logging configuration is managed within the app/Config/Logger.php file. The two most important settings are the threshold and the handlers.
Log Threshold
The $threshold property determines which severity levels of messages are logged. A value of 0 disables logging, while a value of 9 logs everything. You can also specify an array of levels to log only specific types of messages.
| Level | Value | Description |
|---|---|---|
emergency | 1 | System is unusable. |
alert | 2 | Action must be taken immediately. |
critical | 3 | Critical conditions. |
error | 4 | Runtime errors that do not require immediate action but should be logged. |
warning | 5 | Exceptional occurrences that are not errors. |
notice | 6 | Normal but significant events. |
info | 7 | Informational messages. |
debug | 8 | Detailed debug information. |
For example, to log only critical and error messages, you would set: public $threshold = [3, 4];
Sources: source/general/logging.rst
Handlers
Handlers are responsible for taking the log message and writing it to a destination. The default handler is the FileHandler, which writes logs to files in the writable/logs/ directory. You can configure multiple handlers to send logs to different places simultaneously.
The configuration for a handler specifies its class and any parameters it requires, such as the file path for the FileHandler.
Sources: source/general/logging.rst
Using the Logger
The easiest way to write log messages is by using the global log_message() function.
log_message('error', 'The user could not be found.');
log_message('info', 'User {id} logged in from {ip_address}.', ['id' => $user->id, 'ip_address' => $this->request->getIPAddress()]);
The first argument is the log level (e.g., 'error', 'info'), and the second is the message. The function also supports PSR-3 style placeholders, where bracketed words in the message are replaced by values from the third array argument.
Alternatively, you can access the logger instance directly through the Services class:
$logger = \Config\Services::logger();
$logger->error('This is an error message.');
The following diagram shows the sequence of a log message being written.
Summary
CodeIgniter's integrated error handling and logging systems provide a powerful, configurable, and standards-compliant way to manage application stability and diagnostics. By leveraging environment-specific settings, the framework ensures that developers have the tools they need during development without compromising security or user experience in production. The PSR-3 compliant logger further enhances the system's flexibility, allowing for easy integration with a wide range of logging tools and strategies.
Sources: source/general/errors.rst, source/general/logging.rst