Skip to content
PHP Logo

How can one ensure that a log file contains relevant error information when handling exceptions in PHP?

To ensure that a log file contains relevant error information when handling exceptions in PHP, you can catch the exceptions using a try-catch block and then log the error message, file, line number, and stack trace to a log file using a logging library like Monolog.

php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$log = new Logger('error_logger');
$log->pushHandler(new StreamHandler('path/to/logfile.log', Logger::ERROR));

try {
    // Code that may throw an exception
} catch (Exception $e) {
    $log->error('An error occurred: ' . $e->getMessage(), [
        'file' => $e->getFile(),
        'line' => $e->getLine(),
        'stack_trace' => $e->getTraceAsString()
    ]);
}