Log4php Example

As an engineer turned software developer, I’m slowly moving from the world of printf debugging to proper logging. We use log4net at work, and having harnessed a bit of its power, log4php seemed like a natural fit for some debug logging in my migration script. Unfortunately, their configuration format is different and not nearly as well documented.

After much hunting, I finally spent $5 on a single PDF edition of some Canadian PHP magazine that had an article on log4php. Those examples didn’t quite do what I originally wanted, but got me on another path to success. Here’s my configuration:

log4php.xml:

<?xml version="1.0" encoding="ISO-8859-1"?>
<log4php:configuration
  xmlns:log4php="http://www.vxr.it/log4php/"
  threshold="all" debug="true">
 <appender name="default" class="LoggerAppenderEcho">
  <layout class="LoggerLayoutHtml" />
 </appender>
 <root>
  <level value="DEBUG" />
  <appender_ref ref="default" />
 </root>
</log4php:configuration>

bootstrap.inc (or some other high-level include file):

define("LOG4PHP_CONFIGURATION",
 "/full/path/log4php.xml");
define('LOG4PHP_CONFIGURATOR_CLASS',
 '/full/path/log4php/xml/LoggerDOMConfigurator');

And finally, in the actual code class:

require_once('/full/path/log4php/LoggerManager.php');

class ItemAddFromServer extends ItemAddPlugin {

 var $log;

 function ItemAddFromServer() {
   $this->log =& LoggerManager::getLogger('ItemAddFromServer');
 }

 function DoSomething() {
   $this->log->debug('DoSomething');
 }

}

That gives you an HTML table display of your log, which interrupts the flow of your application, but gives you a convenient way to immediately view the results.

No Responses to “Log4php Example”

Leave a Reply