Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...

When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Zend Framework 101: Zend_Log

Creating Your First Logger

To begin, I'll show you how to create a basic file-system logger. To achieve this we must instantiate the Zend_Log class, then add a writer to this object. We will use a writer that writes log messages to the file system.

The class we use to write log messages to the file system is Zend_Log_Writer_Stream. This class accepts the path where the log messages should be written to as the first argument to the constructor.

Note: The path you use must be writable by the web server.

Listing 1 shows an example of creating the logger and adding the writer to it. You can either add the writer when instantiating Zend_Log (such as new Zend_Log(new Zend_Log_Writer_Stream(...))), or as shown in the following listing.

Listing 1 Creating a logger with a filesystem writer (listing-1.php)
    $logger = new Zend_Log();
    $writer = new Zend_Log_Writer_Stream('sample.log');
    $logger->log('sample message!', Zend_Log::INFO);

The above listing concludes by calling the log() method on the Zend_Log object. This records a message to the log. Listing 2 shows an example of how the log file appears after this code is run.

Listing 2 Sample entry in a log file (listing-2.txt)
$ cat sample.log 
2009-04-11T14:47:20+09:00 INFO (6): sample message!

In the next section I'll cover the recording of events in greater detail.

In This Article