Logging

It's extremely important to have logging in your application - things WILL go wrong, and the more insight you have into problems, the better.

Check out Li3's Logger.php - this well-documented class is a good place to start to learn about logging in detail. We're going to add a few basic log messages to our app!

Good news, everybody! It's REALLY EASY to configure logging in Li3!

OK first up we modify app/config/bootstrap.php and add an include:

<?php
// ...

/**
 * This file contains configuration for logging
 */
require __DIR__ . '/bootstrap/logging.php';

// ...

Then, hit http://employee-rolodex.localhost/employees. You should see an error message similar to the following:

Warning: require(employee-rolodex/app/config/bootstrap/logging.php):

failed to open stream: No such file or directory in /var/www/employee-rolodex/app/config/bootstrap.php on line 62

So, we create app/config/bootstrap/logging.php with these contents:

<?php
use lithium\analysis\Logger;

Logger::config(array(
    'default' => array('adapter' => 'Syslog'),
    'problems' => array(
        'adapter' => 'File',
        'priority' => array('emergency', 'alert', 'critical', 'error')
    )
));
?>

OK, now we're going to modify app/controllers/EmployeesController.php a bit:

<?php
namespace app\controllers;

use app\models\Employees;
use lithium\action\DispatchException;
use lithium\analysis\Logger;

class EmployeesController extends \lithium\action\Controller {

    public function index() {
        $employees = Employees::all();
        Logger::alert('Someone listed users...');
        return compact('Employees');
    }

    // ...

Now, hit the URL http://employee-rolodex.localhost/employees to trigger a log write.

Finally, from the terminal, let's have a look at our log file:

$ cat app/resources/tmp/logs/alert.log
2013-12-25 10:47:58 Someone listed users...

Yes, I am writing this on Christmas day!

Did something go wrong? Make sure app/resources/tmp/logs exists and is writeable by your web user.

Right, so what did we do here? Well, we defined two logging destinations - one to the system log, for all logging, and the other, 'problems', to a File. Li3's File logger will log to app/resources/tmp/logs/{message type}.log. Because we used Logger::alert, it created alert.log. If we used "error", it would write to "error.log". Notice also this line:

    'priority' => array('emergency', 'alert', 'critical', 'error')

here, we can see that the file logger is only "paying attention" to 4 types of log events (called "message priority levels". The message priority levels which Logger supports are emergency, alert, critical, error, warning, notice, info and debug. By saying Logger::alert('Someone listed users...');, we are using the alert level. We could equally to Logger::critical or Logger::debug.

Over to you!

That was pretty straightforward, right? At this point, I suggest adding logging to the methods of our controller. Don't worry, I'll wait while you do :-)