Let’s admit, any PHP developer, at some point has “debugged” a PHP application by inserting several “echo” statements here and there. It’s easy and quick but it’s by far not the best way. For one, you can not and should not do anything like that on a production server. The last thing users need to see is debug messages from a desperate developer. Besides, in the ever-increasing Ajaxization of web-applications the “echo approach” simply does not work, anymore. Ajaxized server-side code is executed without having any direct, “echo-compliant” output in the response HTML stream. It’s time to get used to logging to a file on the server.

Unfortunately, at the time of this writing, Drupal does not have built-in support for file logging. Could be because somebody thought the cumbersome database-logging was more than enough, could be because PEAR Log already provides the functionality. Either way, let’s see how we can Integrate PEAR Log in our Drupal development.

First, we need to initialize the logger, by putting the following code in index.php, preferrably after the boostrap and before the call to menu_execute_active_handler().

require_once 'Log.php';
$logconf = array('mode' => 0775, 'timeFormat' => '%X %x');
$logger = &Log::singleton('file', '/tmp/drupear.log', 'ident', $logconf);

We just told logger to log to /tmp/drupear.log file with permission mask 775.

Then, anywhere in the code, where we need output to log

global $logger; //once per scope e.g. once per function body.

$logger->log ( "LOREM IPSUM TESTS. DO NOT TOUCH");

P.S. PHP’s error_log function is another way to log to a file. It is somewhat less flexible compared to PEAR Log, however, so we recommend using the latter, when possible.