# Debugging

Debugging is an inevitable and necessary part of any development
cycle. While CakePHP doesn't offer any tools that directly connect
with any IDE or editor, CakePHP does provide several tools to
assist in debugging and exposing what is running under the hood of
your application.

## Basic Debugging

`function` **debug(mixed $var, ?bool $showHtml = null, bool $showFrom = true)**

- `mixed $var`: The contents to print out. Arrays and objects work well.
- `boolean $showHtml`: Set to true, to enable escaping. Escaping is enabled
  by default when serving web requests. In the console, or when set to false,
  the output is plain text.
- `boolean $showFrom`: Show the line and file the debug() occurred on.

The debug() function is a globally available function that works
similarly to the PHP function print_r(). The debug() function
allows you to show the contents of a variable in a number of
different ways. First, if you'd like data to be shown in an
HTML-friendly way, set the second parameter to true. The function
also prints out the line and file it is originating from by
default.

Output from this function is only shown if the core debug variable
has been set to a value greater than 0.

::: info Changed in version 2.1
The output of `debug()` more resembles `var_dump()`, and uses `Debugger` internally.
:::

## Debugger Class

The debugger class was introduced with CakePHP 1.2 and offers even
more options for obtaining debugging information. It has several
functions which are invoked statically, and provide dumping,
logging, and error handling functions.

The Debugger Class overrides PHP's default error handling,
replacing it with far more useful error reports. The Debugger's
error handling is used by default in CakePHP. As with all debugging
functions, `Configure::debug` must be set to a value higher than 0.

When an error is raised while debug is enabled, Debugger outputs information to the
page. When debug is 0, errors are written to the error log
(`logs/error.log` by default) instead; see [Error Handling](https://pieceofcake2.github.io/docs/development/errors.md).
The error report
that is generated has both a stack trace and a code excerpt from
where the error was raised. Click on the "Error" link to
reveal the stack trace, and on the "Code" link to reveal the
error-causing lines.

## Using the Debugger Class

`class` **Debugger**

To use the debugger, first ensure that Configure::read('debug') is
set to a value greater than 0.

`static` Debugger::**dump**($var, $depth = 3)

Dump prints out the contents of a variable. It will print out all
properties and methods (if any) of the supplied variable:

```php
$foo = [1,2,3];

Debugger::dump($foo);

// outputs
[
    1,
    2,
    3
]

// simple object
$car = new Car();

Debugger::dump($car);

// outputs
Car
Car::colour = 'red'
Car::make = 'Toyota'
Car::model = 'Camry'
Car::mileage = '15000'
Car::accelerate()
Car::decelerate()
Car::stop()
```

::: info Changed in version 2.1
In 2.1 forward the output was updated for readability. See `Debugger::exportVar()`
:::

::: info Changed in version 2.5.0
The `depth` parameter was added.
:::

`static` Debugger::**log**($var, $level = 7, $depth = 3)

Creates a detailed stack trace log at the time of invocation. The
log() method prints out data similar to that done by
Debugger::dump(), but to the `debug.log` instead of the output
buffer (`logs/debug.log` with the default log configuration). Note your
`logs/` and `tmp/` directories (and their contents) must be writable by the
web server for log() to work correctly. In the legacy layout, logs are written
to `app/tmp/logs/`.

::: info Changed in version 2.5.0
The `depth` parameter was added.
:::

`static` Debugger::**trace**($options)

Returns the current stack trace. Each line of the trace includes
the calling method, including which file and line the call
originated from.

```text
// In PostsController::index()
pr(Debugger::trace());

// outputs
PostsController::index() - APP/Controller/PostsController.php, line 48
Dispatcher::_invoke() - CORE/Cake/Routing/Dispatcher.php, line 190
Dispatcher::dispatch() - CORE/Cake/Routing/Dispatcher.php, line 163
[main] - ROOT/webroot/index.php, line 61
```

In the trace, `APP` stands for your application directory (`src/` in the
modern layout), `CORE` for the framework's `src/` directory and `ROOT` for
the project root.

Above is the stack trace generated by calling Debugger::trace() in
a controller action. Reading the stack trace bottom to top shows
the order of currently running functions (stack frames). In the
above example, `index.php` called Dispatcher::dispatch(), which
in-turn called Dispatcher::\_invoke(). The \_invoke() method then
called PostsController::index(). This information is useful when
working with recursive operations or deep stacks, as it identifies
which functions are currently running at the time of the trace().

`static` Debugger::**excerpt**($file, $line, $context = 2)

Grab an excerpt from the file at \$file (which is an absolute
filepath), highlights line number \$line with \$context number of
lines around it. Each line is highlighted with `highlight_string()`, and the
requested line is wrapped in `<span class="code-highlight">`:

```php
pr(Debugger::excerpt(APP . 'Controller' . DS . 'PostsController.php', 48, 2));

// will output an array of 5 HTML strings:
// lines 46-47, line 48 (wrapped in <span class="code-highlight">), and lines 49-50
```

Although this method is used internally, it can be handy if you're
creating your own error messages or log entries for custom
situations.

`static` Debugger::**exportVar**($var, $depth = 3)

Converts a variable of any type to a string for use in debug
output. This method is also used by most of Debugger for internal
variable conversions, and can be used in your own Debuggers as
well.

::: info Changed in version 2.1
This function generates different output in 2.1 forward.
:::

`static` Debugger::**getInstance**($class = null)

Returns the Debugger singleton. Pass a class name to replace the CakePHP
Debugger with an instance of your own Debugger subclass.

`static` Debugger::**getType**($var)

Get the type of a variable. Objects will return their class name

::: info Added in version 2.1
:::

## Debug Error Pages {#debug-error-pages}

::: pieceofcake2
Since v2.12.6, in debug mode (`debug` > 0) the core error pages (missing
controller, action, view or layout, database errors, and uncaught exceptions
without an application `error400.ctp` / `error500.ctp`) use a `dev_error`
layout ported from CakePHP 5. It shows the error title and the exception
class, the suggested fix with the real file path, and a stack trace of the
exception and its previous exceptions with code excerpts for every frame and
`(edit)` links that open the file in your editor.

The links open PhpStorm by default. To use another editor, set
`Debugger.editor` to `atom`, `emacs`, `macvim`, `sublime`, `textmate`,
`vscode` or `vscodium`. When the application runs in a container, set
`Debugger.editorBasePath` to the application path on your machine:

```php
// config/core.php
Configure::write('Debugger.editor', 'vscode');
Configure::write('Debugger.editorBasePath', '/home/me/projects/my_app');
```

`Debugger::editorUrl()`, `Debugger::setEditor()` and `Debugger::addEditor()`
work as in CakePHP 5. Production mode (`debug` = 0) and the console are
unchanged. Error templates provided by your application, plugin or theme keep
rendering in your layout, and a `Layouts/dev_error.ctp` (or
`layout/dev_error.php`) in the application or theme overrides the core layout,
`templates/layout/dev_error.php` of the framework. See
[Migrating from CakePHP 2.10](https://pieceofcake2.github.io/docs/appendices/migrating-from-cakephp-2-10.md#dev-error-pages)
for how to keep the old look.

Since the release after CakePHP 2.13.0, the core error templates switch layouts
as in CakePHP 5: AJAX requests in debug mode also get this page, and the core
`error400` and `error500` templates use the `error` layout in production mode.
See [Layouts of the core error pages](https://pieceofcake2.github.io/docs/appendices/migrating-from-cakephp-2-10.md#error-page-layouts).
:::

## Using Logging to debug

Logging messages is another good way to debug applications, and you can use
`CakeLog` to do logging in your application. All objects that
extend `CakeObject` (controllers, components, models and so on) have an
instance method `log()` which can be used to log messages:

```php
$this->log('Got here', 'debug');
```

The above would write `Got here` into the debug log. You can use log entries
to help debug methods that involve redirects or complicated loops. You can also
use `CakeLog::write()` to write log messages. Framework classes are autoloaded,
so this method can be called statically anywhere in your application:

```php
CakeLog::write('debug', 'Got here');
```

## Debug Kit

DebugKit is a plugin that provides a number of good debugging tools. It adds
a small CakePHP icon to the bottom right-hand corner of your HTML pages.
Clicking it opens a toolbar with panels that show information about the
current request, such as the SQL queries, timers, log messages, view variables
and session data. The History panel lists previous requests, including
redirects and ajax requests, so you can inspect them too.
Use [pieceofcake2/debug_kit](https://pieceofcake2.github.io/debug_kit/), a
PHP 8 compatible version of DebugKit 2.x maintained by the Piece of Cake 2
project. Install it as a development dependency with Composer:

```bash
composer require --dev pieceofcake2/debug_kit
```

Then load the plugin in `config/bootstrap.php`:

```php
// config/bootstrap.php
CakePlugin::load('DebugKit');
```

See the
[DebugKit documentation](https://pieceofcake2.github.io/debug_kit/)
for how to enable the toolbar, the toolbar panels and their configuration, and
how to write your own panels. See [Maintained Plugins](https://pieceofcake2.github.io/docs/plugins/maintained-plugins.md)
for the other maintained plugins.

## Xdebug

If your environment supplies the Xdebug PHP extension, fatal errors will show
additional Xdebug stack trace details. Details about Xdebug can be found at
[Xdebug](https://xdebug.org) .
