Logging and errors
When something goes wrong you need to find out what exactly happened. A log is a set of files where the application records events and errors. An exception is a way to stop an action and show the visitor an error page. CakePHP has ready tools for both.
Where the log is
Log files are in the logs folder in the project root: errors go to logs/error.log and other records to logs/debug.log. This is configured in the Log section of config/app.php.
Writing to the log
// src/Controller/ArticlesController.php
use Cake\Log\Log;
public function view(int $id): void
{
Log::info("Article $id was opened");
$this->set('article', $this->Articles->get($id));
}Open /articles/view/1 and look into logs/debug.log: a line with the date, the info level and the message text appears at the end.
Levels
| Method | When to use | File |
|---|---|---|
Log::debug() | Details for the developer | debug.log |
Log::info() | An ordinary event | debug.log |
Log::warning() | Something suspicious | error.log |
Log::error() | An error that needs attention | error.log |
The framework writes unhandled exceptions to error.log by itself, together with the request address and the stack trace.
The debug function
debug($article);debug() prints a variable right on the page together with the file and line of the call. It works only in development mode. The dd() function does the same and stops execution.
An error page from an action
use Cake\Http\Exception\NotFoundException;
public function view(int $id): void
{
$article = $this->Articles->get($id);
if (!$article->published) {
throw new NotFoundException('Article not found.');
}
$this->set(compact('article'));
}throw interrupts the action and the visitor gets a page with the 404 code. To the visitor an unpublished article looks the same as a missing one.
Ready-made exceptions
| Class | Code |
|---|---|
BadRequestException | 400 |
ForbiddenException | 403 |
NotFoundException | 404 |
MethodNotAllowedException | 405 |
InternalErrorException | 500 |
All of them are in the Cake\Http\Exception namespace.
What an error looks like
In development mode (debug is true) the error page shows the exception text, the file, the line and the stack trace. On a production server (debug is false) the visitor sees a short page without details.
These short pages are ordinary templates and can be changed:
| Template | For which errors |
|---|---|
templates/Error/error400.php | 404 and other request errors |
templates/Error/error500.php | Server errors |
Their frame is set by the templates/layout/error.php layout.
Common mistake
On a production server the page says only "An Internal Error Has Occurred", and people start fixing it at random or turn on debug right on the server. Neither is needed: the full error text with the file and line is already written to logs/error.log. Open the log first.