Benjamin Tigano Developer at Large

Adding logging capabilities

The ability to log data in our application can be for statistical, development, debug, or monitoring purposes. Zend offers various different log writers and formatters, but for simplicity's sake, we are going to use the default format, and the Zend_Log_Writer_Stream writer so that we can log information to a file. If you want more information about the other log writers and formatters, check out the Zend_Log section of the programmer's reference guide, here.

Let's begin! We first want to create a directory that we can store our log files in. I'm going to store mine in the project root, and call the directory logs. This directory will need to be writable by your web server.

Next, let's add an entry to our application.ini configuration file to tell Zend Framework about the directory we just created, and the name of the file we want to use. Here's the line that you should add to the [production] section:

logging.file = APPLICATION_PATH "/../logs/debug.log"

The next changes will be made to the Bootstrap.php file in our application directory. First thing I like to do is store the application configuration in the Zend_Registry so that we can access it in other parts of our application. This saves us the hassle/overhead of creating that Zend_Config object more than once during the life of the request. Here is the method we'll be adding to our Bootstrap.php class:

protected function _initConfig()
{
    $config = new Zend_Config($this->getOptions(), false);
    Zend_Registry::set('config', $config);
    return $config;
}

Just below that newly added method, we'll add in another method to create our Zend_Log object, and then we'll store that in the Zend_Registry so that we can access that around our application as needed:

protected function _initLogging()
{
    $logger = new Zend_Log(new Zend_Log_Writer_Stream(Zend_Registry::get('config')->logging->file));
    Zend_Registry::set('logger', $logger);
    return $logger;
}

At this point, our logger is set up, and we can use all across our application. Let's add in a line to the indexAction of our IndexController so that when we go to our project's root, it will store something in the log. Add the following line to the indexAction method in the IndexController file:

Zend_Registry::get('logger')->info('IndexController->IndexAction called!');

Now, navigate to http://localhost/index and verify that a new line has been added to your logs/debug.log file:

2012-02-24T13:31:45-05:00 INFO (6): IndexController->IndexAction called!

You can also try navigating to http://localhost/index/alternate and verify that a new row is NOT added (since our call to log data was only in the indexAction, not the alternateAction.)

That wraps up this section!

Download the project

Next up, we'll be adding page caching capabilities.

Fork me on GitHub