Logging

Rhapsody includes a simple but effective file-based logger, managed by the Rhapsody\Core\Logger class. It provides a standardized way to write messages to log files for debugging, tracking errors, or recording important events in your application.


Configuration

To use the logger, you first need to tell the framework where your log files are located. This is done in the config.php file within the logging array. You can define paths for different log types, such as PHP and Apache errors.

// in config.php
'logging' => [
    // Example for MAMP on macOS
    'php_error_log_path' => '/Applications/MAMP/logs/php_error.log',
    'apache_error_log_path' => '/Applications/MAMP/logs/apache_error.log',
    // You can also define a custom log path
    'application_log_path' => dirname(__DIR__) . '/storage/logs/app.log',
],

The logger will automatically create the directory if it does not exist when you write to it.


Basic Usage

To use the logger, you create a new instance of the Rhapsody\Core\Logger class, passing the path to the desired log file in its constructor.

Writing to a Log

The log() method is used to write messages. It automatically adds a timestamp and a log level to each entry.

use Rhapsody\Core\Logger;

// Get the path from your config
$logPath = $config['logging']['application_log_path'];
$logger = new Logger($logPath);

// Write an informational message
$logger->log('User successfully updated their profile.', 'INFO');

// Write an error message
try {
    // ... some operation that might fail ...
} catch (\Exception $e) {
    $logger->log('Failed to process payment: ' . $e->getMessage(), 'ERROR');
}

This will produce entries in your storage/logs/app.log file like this:

[2025-10-02 22:30:00] INFO: User successfully updated their profile.
[2025-10-02 22:30:01] ERROR: Failed to process payment: Connection timed out.

Reading from a Log

The read() method allows you to retrieve the last N lines of a log file. This is particularly useful for displaying recent activity or errors, as seen in the developer toolbar.

use Rhapsody\Core\Logger;

$phpErrorLog = new Logger($config['logging']['php_error_log_path']);

// Read the last 50 lines of the PHP error log
$recentErrors = $phpErrorLog->read(50);

echo "<pre>{$recentErrors}</pre>";

Error Logging

For uncaught exceptions, PHP errors, and fatal shutdown errors, Rhapsody uses a global error handler that logs everything to a dedicated error log file. See the Error Handling & Logging documentation for details.