PHP 7: Maintaining and Upgrading Legacy Apps · Working in a Legacy PHP Codebase
Debugging and Logging Legacy Apps
Use Xdebug, error logs and structured logging to understand production behavior.
Configure error logging properly (log_errors=On, error_log path, error_reporting=E_ALL, display_errors=Off in production), use Xdebug 3 step debugging locally (xdebug.mode=debug), and introduce Monolog for structured logs with request IDs. Error tracking services (Sentry, Bugsnag) group exceptions and show stack traces with context — often the fastest way to discover what a legacy app is actually doing wrong.
<?php
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Monolog\Formatter\JsonFormatter;
$requestId = $_SERVER['HTTP_X_REQUEST_ID'] ?? bin2hex(random_bytes(8));
$handler = (new StreamHandler('php://stderr', Logger::INFO))->setFormatter(new JsonFormatter());
$log = new Logger('app', [$handler]);
$log->pushProcessor(function (array $record) use ($requestId) {
$record['extra']['request_id'] = $requestId;
return $record;
});
$log->warning('Payment retry', ['order_id' => $orderId, 'attempt' => 2]);
Common pitfalls
- Debugging production by enabling
display_errors. - Leaving Xdebug installed in production (big slowdown).
- Logging without context, so log lines can't be correlated.
Key points
- Log errors, never display them in production
- Xdebug for local step debugging
- Structured logs with request IDs; error tracking
Further reading: Xdebug: step debugging
Practice questions
Why is error tracking (e.g., Sentry) especially useful in legacy apps?
Answer
It groups recurring exceptions with stack traces, request data and frequency, revealing real-world failures that nobody documented.
What's the risk of enabling Xdebug in production?
Answer
It significantly slows every request and, with debugging enabled, can expose a remote debugging connection. Keep it to development environments.
Open in the app to mark lessons complete, take notes and track your progress.