You are browsing the unmaintained documentation for old Nette 2.1. See documentation for current Nette.

Debugging and Error Handling

Library Nette\Diagnostics\Debugger that have become naturalized under the name Laděnka is a useful everyday helper PHP programmer. It will help you

  • quickly detect and correct errors
  • log errors
  • as listing variables
  • and measure the time

PHP is a language for chopping hardly stripped errors as perfect as it gives developers a great deal of flexibility. That is a valuable debugging tool Nette\Diagnostics\Debugger. Among the diagnostic tools for PHP is the ultimate. If you are now experiencing Laděnkou first time, believe me, your life starts to divide Laděnkou the one before and the one with her. Welcome to the good part!

Laděnku easily activate, simply enter the code, preferably immediately after the reading framework, add:

use Nette\Diagnostics\Debugger;

Debugger::enable(); // activate Laděnku

The first thing you notice on the site, Debugger Bar.

Debugger Bar

Debugger Bar is a floating panel that is displayed in the lower right corner of the page. We can move the mouse, and after reloading the page will remember its position.

You can add other useful panels into the Debugger Bar. You can find interesing ones in addons or you can create your own.

Visualization of errors and exceptions

Surely you know how PHP reports errors: in the source code of the page will output something like this:

Parse error:  syntax error, unexpected T_STRING in DashboardPresenter.php on line 8

or uncaught exception:

Fatal error:  Uncaught exception 'MemberAccessException' with message 'Call to undefined method Nette\Http\User::isLogedIn().' in D:\Web\Nette.web\libs\Nette\ObjectMixin.php:69
Stack trace:
#0 D:\Web\Nette.web\libs\Nette\Object.php(80): ObjectMixin::call(Object(User), 'isLogedIn', Array)
#1 [internal function]: Object->__call('isLogedIn', Array)
#2 D:\Web\cd-collection\app\presenters\DashboardPresenter.php(12): User->isLogedIn()
#3 D:\Web\Nette.web\libs\Nette\Application\Presenter.php(154): DashboardPresenter->startup()
#4 D:\Web\Nette.web\libs\Nette\Application\Application.php(148): Presenter->run(Object(PresenterRequest))
#5 D:\Web\cd-collection\app\bootstrap.php(54): Application->run()
#6 D:\Web\cd-collection\index.php(13): require('D:\Web\cd-colle...')
#7 {main}
  thrown in D:\Web\Nette.web\libs\Nette\ObjectMixin.php on line 69

In this extract is not very easy to navigate. If we switch Laděnku, error or exception is displayed completely in a different form:

Uncaught exception in design Nette\Diagnostics\Debugger

Error message literally screams, we see part of the source code with the highlighted line where the error occurred, information Call to undefined method Nette\Http\User::isLogedIn() clearly explains your error is. The entire site is also live, we can click through to more detail. Try it.

And you know what? In this way, capture and display a fatal error. Without the need to install any extension.

Errors as a typo in a variable name or an attempt to open a nonexistent file, generate reports of level E_NOTICE or E_WARNING. These can be in graphics page makes it easy to overlook even be visible at all (except by looking at the page code).

Debugger::$strictMode = TRUE;

To detect typos even when assigned to an object variable, we inherit his class from Nette\Object.

We can also change the depth of nesting by Debugger::$maxDepth and length label displayed by Debugger::$maxLen. Lower values ​​laděnku naturally accelerates.

Debugger::$maxDepth = 2; // default: 3
Debugger::$maxLen = 50; // default: 150

Production mode and error logging

As you can see, is quite eloquent Laděnka, which can be appreciated in the development environment, while on the production server it would cause disaster ready. There is no debugging information list can not. Laděnka therefore has autodetection environment and where to run stark example of a server error instead of showing zaloguje a visitor sees only user-comprehensible message:

Output mode suppresses all debugging information that we send out via Debugger::dump() or Debugger::fireLog(), and of course all the error messages generated by PHP. So if you have forgotten the code Debugger::dump($obj), do not have to worry about on a production server does not list anything.

The mode switching is used the first parameter of Debugger::enable(), where you can specify either a constant Debugger::PRODUCTION or Debugger::DEVELOPMENT.

If it is not specified, the default value of Debugger::DETECT in which case the system detects a server by IP address – if available via the public IP address running in production mode, where the local and the developer. In most cases it is not necessary to set the mode to recognize and correctly depending on whether you are launching an application on your local server or in production.

In production mode automatically Laděnka all errors and exceptions captured logs to a text log. Unless you specify otherwise, it will be a set of log/error.log . Error while logging is extremely useful. Imagine that all users of your application are actually betatesters who are doing cutting-edge work for free in search of bugs and you do stupid if you threw away their valuable reports unnoticed to the recycle bin.

If you need a log in your own message or you caught an exception, use the method log():

Debugger::log('Unexpected error'); // text message

try {
    failureOperation();
} catch (Exception $e) {
    Debugger::log($e); // log exception
    // or Debugger::log($e, Debugger::ERROR) // sends also an email notification
}

Different directory for logging errors can be set by the second parameter methods enable():

Debugger::enable(Debugger::DETECT, __DIR__ . '/mylog');

Ringer for the real error log is a key source of information and wants to be informed immediately of any new error. Laděnka him in that caters to, is capable of a new record in the log inform you by e-mail. Where do you send the e-mails we identify the variable $email:

Debugger::$email = 'admin@example.com';

Alternatively, it is possible to set this in the configuration file:

common:
    nette:
        debugger:
            email: admin@example.com

However, in order to overwhelm you e-mail box, sends only one message and creates a file email-sent. Developer when you receive e-mail notifications check the log, correct application and monitoring deletes a file, which in turn activates the sending of e-mails.

Dump variables

Each tuner is a good friend with the function var_dump in detail, lists the contents of the variable. Unfortunately, the environment loses HTML formatting and extract decanted into a single line of HTML code sanitizaci not to mention. In practice, it is necessary var_dump replace handier functions. That is just Debugger::dump().

$arr = array(10, 20.2, TRUE, NULL, 'hello');

Debugger::dump($arr);
// including namespace Nette\Diagnostics\Debugger::dump($arr);

generates the output:

array(5) {
  [0] => int(10)
  [1] => float(20.2)
  [2] => bool(true)
  [3] => NULL
  [4] => string(5) "hello"
}

Timing

Another useful tool is the debugger stopwatch accurate to microseconds:

Debugger::timer();

// sweet dreams ma cherrie
sleep(2);

$elapsed = Debugger::timer();
// $elapsed ? 2

An optional parameter can be achieved by multiple measurements.

Debugger::timer('page-generating');
// some conde
Debugger::timer('rss-generating');

// some code
$rssElapsed = Debugger::timer('rss-generating');
$pageElapsed = Debugger::timer('page-generating');
Debugger::timer(); // runs timer

... // some difficult operation

echo Debugger::timer(); // elapsed time in seconds

Firebug and FireLogger

We can not always send debugging information to the browser window. This applies to Ajax requests, or generate XML output files. In such a case, we can send messages to a separate channel in Firebug. Errors Notice and Warning levels are to Firebug window even sent automatically. It is also possible to log exceptions caught while an application, but it is worth it to draw attention to them.

How to do it?

  1. download and run Firefox browser
  2. download extension Firebug
  3. download extension FireLogger
  4. restart browser, turn on Firebug (F12 key) and enable network (Net) and Logger

… Open our utility panel and click on the Console. Ha! I moved error message.

Because Nette\Diagnostics\Debugger communicates with Firebug via HTTP headers, you must call the logging function even before the PHP script sends anything to the output. It is also possible to enable output buffering and the output delay.

use Nette\Diagnostics\Debugger;

Debugger::fireLog('Hello World'); // render string into Firebug console

Debugger::fireLog($_SERVER); // or even arrays and objects

Debugger::fireLog(new Exception('Test Exception')); // or exceptions

The result looks like this:

Laděnka at your service

Nette Framework is designed as an open framework. This means that the individual components can be used separately in their applications. This also applies to Nette\Diagnostics\Debugger. Nothing prevents you from a pleasant life that at the beginning of each script run Laděnku.