Adding Configurable Logging to Your PHP Scripts

This tip shows how to add logging to your PHP script and how to add configuration so you have basic, configurable logging. The PHP script requires two PEAR packages, Log and Config. To use the code in shown in this tip, you'll need to PEAR installed along with PHP and you'll need to install both the Log and the Config PEAR packages. To install the two packages type:

      pear install Log Config

The Configuration File

The Config package supports several different configuration sources, including XML and the standard INI file format. INI configuration files can have one or more sections in them, such as the [Logging] section shown in this example. Shown here is a simple INI file example, containing two keys for the logging configuration: the log_file key which contains the full path to the log file and the log_level key, which contains a string representation of the minimum logging level that will be logged.

      [General]
      # Some configuration values here.

      [Logging]
      log_file=C:\path\to\logs\logfile.txt
      log_level=error

The Code

The PHP script that uses the two packages looks like this:

      parseConfig('C:\\path\\to\\my.ini', 'IniFile');
      if (isset($configRoot)) {
         $settings = $configRoot->toArray();
      } else {
         throw Exception("Unable to load configuration.");
      }

      $logfile = $settings['root']['Logging']['log_file'];
      $loglevel = $settings['root']['Logging']['log_level'];

      # Create the instance of the logger
      $logger = &Log::factory('file', $logfile, 'MyScript');
      # Transforms the string, 'error' to an integer priority to use for
      # calculating the mask.
      $mask = Log::MAX($logger->stringToPriority($loglevel));
      # Sets the mask for the logger.
      $logger->setMask($mask);

      # Now try logging a bunch of messages to see what happens

      $logger->debug('My debug message');
      $logger->info('My info message');
      $logger->notice('My notice message');
      $logger->warning('My warning message');
      $logger->err('My error message');
      $logger->crit('My critical message');
      $logger->alert('My alert message');
      $logger->emerg('My emergency message');
      ?>

The Results

When you run the script, you'll get the following output:

      Nov 20 13:34:58 MyScript [error] My error message
      Nov 20 13:34:58 MyScript [critical] My critical message
      Nov 20 13:34:58 MyScript [alert] My alert message
      Nov 20 13:34:58 MyScript [emergency] My emergency message

How it Works

When the script runs, the Config class parses the INI file and puts the sections and keys into an associative array structure. The array element root is always the root element, then the section header is nested within root, with the keys (log_file and log_level) associated with the section header. To access the log_file value, the script uses

      $settings['root']['Logging']['log_file'].

The Log::MAX() method tells the logger to set a mask that will mask everything from debug to a maximum of error. This will mask anything considered less important in priority than an error, blocking those less important messages from being written to a log.

Adding configurable logging levels to your PHP scripts can be a good way to eliminate "scrolling blindness", which occurs when there are too many logging messages to sift through.

For a great reference to these PEAR packages and more, get Foundations of PEAR: Rapid PHP Development by Nathan A. Good and Allan Kent. Published by APress. http://www.apress.com/book/bookDisplay.html?bID=10181. Excerpted with permission, published by Apress (ISBN 1-59059-739-7).

About the Authors

Nathan A. Good lives in the Twin Cities area in Minnesota. He is a software developer, systems administrator, and author. He has written and co-written several books and articles on open source technologies.

Allan Kent is a born and bred South African and still lives and works in Cape Town. He has been programming in various languages and on diverse platforms for more than 20 years. He's currently the head of technology at Saatchi & Saatchi Cape Town.
__________________________

Load Disqus comments