Adding Configurable Logging to Your PHP Scripts

April 30th, 2008 by LJ Staff in

Your rating: None

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.
__________________________

__________________________


Special Magazine Offer -- Free Gift with Subscription
Receive a free digital copy of Linux Journal's System Administration Special Edition as well as instant online access to current and past issues. CLICK HERE for offer

Linux Journal: delivering readers the advice and inspiration they need to get the most out of their Linux systems since 1994.

Post new comment

Please note that comments may not appear immediately, so there is no need to repost your comment.
The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <pre> <ul> <ol> <li> <dl> <dt> <dd> <i> <b>
  • Lines and paragraphs break automatically.

More information about formatting options

Newsletter

Each week Linux Journal editors will tell you what's hot in the world of Linux. You will receive late breaking news, technical tips and tricks, and links to in-depth stories featured on www.linuxjournal.com.
Sign up for our Email Newsletter

Tech Tip Videos

From the Magazine

July 2009, #183

News Flash: Linux Kernel 3.0 to include an on-the-go Expresso machine interface! Ok, maybe not, but Linux is definitely going mobile, from phones to e-readers. Find out more inside about Android, the Kindle 2, the Western Digital MyBook II, The Bug, and Indamixx (a portable recording studio). And if you've gone mobile and you been wanting more Emacs in your life then check out Conkeror.


To compliment the mobile we've got the stationary: parsing command line options with getopt, checking your Ruby code with metric_fu, and building a secure Squid proxy. How is this stationary you ask? What can we say? It's not. We just wanted to see if anybody actually read this part of the page :) .


All this and more, and all you have to do is get your hot sweaty hands on the latest copy of Linux Journal.





Read this issue