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.
__________________________
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- Designing Electronics with Linux
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Dynamic DNS—an Object Lesson in Problem Solving
- Using Salt Stack and Vagrant for Drupal Development
- Build a Skype Server for Your Home Phone System
- New Products
- Why Python?
- A Topic for Discussion - Open Source Feature-Richness?
- Validate an E-Mail Address with PHP, the Right Way
- Tech Tip: Really Simple HTTP Server with Python
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?



1 hour 47 min ago
4 hours 17 min ago
14 hours 19 min ago
18 hours 46 min ago
22 hours 22 min ago
22 hours 55 min ago
1 day 1 hour ago
1 day 1 hour ago
1 day 1 hour ago
1 day 5 hours ago