Home arrow PHP arrow Page 4 - PHP Application Development Part Two

Event Logging - PHP

Building on what we learned in part one, this article discusses data storage, system configuration, error handling and logging. Read on to find out how practicing the proper use of these concepts can simplify application maintenance and testing, and accelerate system debugging.

TABLE OF CONTENTS:
  1. PHP Application Development Part Two
  2. Storing Dynamic Data
  3. Error Handling
  4. Event Logging
By: David Fells
Rating: starstarstarstarstar / 36
March 08, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Event logging is exactly what the name suggests – the recording of events in an application. Logging is most often associated with error logging and authentication logging, but can be used for a much wider array of problems. Logging can be used to track visitor statistics, form submissions, and database activities. Logging can even be used to catalog script execution step by step in a meaningful way that allows developers to review a detailed execution path with relevant data to isolate script problems. In most applications, error logging and authentication logging are the extent of what is needed, but be creative and use logs to your advantage when trying to solve more complex problems.

Storing our log files presents the same general decisions as choosing how to store our application data. I prefer logging to a database to simplify the collection of statistical data. There is a problem with that approach though – can you guess? What happens when our application cannot access the database used for logging?

This is where flat file logging comes in handy. When writing code to handle logging to a database, it is wise to always code your logging tool to switch over to a flat file when a database is not available. Consider the following extremely basic logging class.

<?php
class Log
{
 var $settings;
 var $dbh;
 var $method;

 function Log(&$settings, &$dbh)
 {
  $this->settings = &$settings;
  $this->dbh = &$dbh;
  $this->method = ‘db’;

  if (gettype($this->dbh) != ‘resource’)
  {
   $this->dbh = mysql_connect($settings[‘db’][‘host’],
                 $settings[‘db’][‘user’],
                 $settings[‘db’][‘pass’]);
  } 

  if (gettype($this->dbh) != ‘resource’)
  {
   $this->method = ‘file’;
  }
 } 

 function record($message)
{
 switch ($this->method)
 {
  case ‘file’ :
return $this->recordToFile($message);
   break;
  case ‘db’ :
   return $this->recordToDb($message);
   break;  
 }
}
}
?>

You can use your imagination for the “recordToFile” and “recordToDb” methods, as the intent is clear. Obviously the object would need to know the name of the file to which log messages should be appended; we can accomplish this by storing the path to the log file in settings or by telling the log explicitly where to write. We can also extend this class to log in different formats or even use subclassing to determine which logfiles are written to.

You can also use your imagination to tangle up the “Error” and “Log” classes discussed above in all sorts of ways. The following example shows a basic way to configure the error object with a logging object. The example will also demonstrate the use of multiple debugging levels to determine what information is logged. Assume all class and configuration code from above is available to this script. There are a couple of new methods on the error handler here, but the usage is obvious and I will not define the code for those methods.

<?php
define(‘DEBUG_LEVEL’, 1);

require_once(‘class.log.php’);
$log = &new Log(&$settings, NULL);

if (DEBUG_LEVEL > 0)
{
 $log->record(‘PID ‘.getmypid().’ Started’);
}

require_once(‘class.error.php’);
$errorHandler = &new Error();
$errorHandler->setLog(&$log);
set_error_handler(array(&$errorHandler, ‘setError’));

if (DEBUG_LEVEL > 0)
{
 $log->record(‘Trying database connection’);
}

$dbh = @mysql_connect($settings[‘db’][‘host’],
        $settings[‘db’][‘user’],
        $settings[‘db’][‘pass’]);

if (gettype($dbh) != ‘resource’)
{
 trigger_error(‘Unable to connect to database’);
}
elseif (DEBUG_LEVEL > 0)
{
 $log->record(‘Database connection established’);
}


if (DEBUG_LEVEL > 0)
{
 $log->record(‘PID ‘.getmypid().’ Ended’);
}

?>

In this example, setting “DEBUG_LEVEL” to 0 causes the script to only record catastrophic errors, whereas setting it to 1 will cause the script to record every action taken. In a situation where our task was performed by another object, we would want to be sure that the object knew as little about the error object as possible – basically the “setError” method. This allows us to pass any subclass of the error object to our class without changing code in the dependant class.

Like many of the practices discussed thus far, the most important thing about logging is that you use it. Logging is an invaluable tool for maintaining an application. It is the only method by which detailed application information can be captured transparently and stored for later review. This information can, when provided in sufficient detail and context, provide a conceptual window through which to view a system problem.

A quick note – you probably noticed that I did not choose to use a database abstraction layer in my example code. There are a few reasons for this, the first of which is brevity. I do not care to delve into which layer is the best and how they work. Next, most PHP applications do not need a database abstraction layer. It is not the norm for PHP applications to require portability to other databases, and even though the need does exist at times we should use classes judiciously and avoid them when they are not needed.

Finally, I want to preempt the common argument that an abstraction layer enforces uniform access methods throughout code. Anyone familiar with ADODB or PEAR::DB knows full well that these packages are a mess and allow you to interact with a database in a variety of methods, each inconsistent with the other in theory and implementation. While these layers have their usage, they do not belong in most Web applications. Adhering to conventions and writing clean code will solve for uniformity, with or without an abstraction layer.

Conclusion

This article has covered some important fundamentals for PHP application development. Building on what we discussed in part one, we examined data storage, system configuration, error handling and logging. Though the exploration of each was brief, the overall purpose of each was clear. Practicing the use of these concepts greatly simplifies application maintenance and testing and, if used properly, it can accelerate system debugging radically.

My implementations are not necessarily “the” way to practice these concepts, they are simply the way I have learned through experience and study to handle them. I encourage you with this, as with any new idea, to poke and prod at it and form your own opinions. The article is intentionally light on code to facilitate this. If you analyze the problem and form your own solutions using the contents of this article as a sort of guide, you will find a solution to most any problem these concepts can solve.

In the next article we will discuss some basic database planning considerations and naming conventions for databases and discuss user authentication and management. See you then!



 
 
>>> More PHP Articles          >>> More By David Fells
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: