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.

      # Some configuration values here.


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.

      # 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


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


White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState