Categories
Posts

PHP Helpers: debug_log

I’ve been thinking recently about useful PHP functions, ones that are so handy that I’d like to have them available in every PHP code base I work on. These aren’t necessarily big elaborate functions, they do a single task and do it well. So I’ll be writing a series of posts called ‘PHP Helpers’. I’ve started a php-helpers.php file to keep these in.

The first PHP Helpers function is debug_log

[sourcecode lang=”php”]
if ( !function_exists( ‘debug_log’ ) ) {
function debug_log( $msg, $file = ‘/tmp/debug.txt’ ) {
$msg = gmdate( ‘Y-m-d H:i:s’ ) . ‘ ‘ . print_r( $msg, TRUE ) . "n";
error_log( $msg, 3, $file );
}
}
[/sourcecode]

This function is wrapped in a function_exists check to make sure that it doesn’t collide with an existing function of the same name. I could have put this in a separate class, but I wanted to treat these as first class functions.

This function takes a variable and writes it out to log file (/tmp/debug.txt by default). The variable can be a string, integer, float, array or object (basically any PHP type) since it gets passed through print_r for processing. Each log entry gets a time stamp to make it easy to keep track of the different entries.

To write an entry to the debug log it uses the error_log function, which makes it easy to append new lines to a text file.

Here’s a very simple and contrived example of how to use the function:

[sourcecode lang=”php”]
$data = array(
‘name’ => ‘Joseph’,
‘url’ => ‘http://josephscott.org/’
);

debug_log( $data );
[/sourcecode]

The log entry in /tmp/debug.txt looks like:

[sourcecode]
2010-01-14 18:01:37 Array
(
[name] => Joseph
[url] => http://josephscott.org/
)
[/sourcecode]

Nothing flashy, just a simple way to log information to a separate file.

2 replies on “PHP Helpers: debug_log”

I was lately also thinking of starting a little set of generic functions. I also made a little log function recently.

One of the things I ran into was the filename which you set by default and I had the same idea (i made one log functions for a html log and one for a clear text log) (the html log shows different colors based on the importance)


function EDL_HTML_LOG($msg="undefined", $level=0, $logDirFile='log/log.html') {

But… if one of the apps has a different location for the log file that would not be handy repeating it over and over. So I made a little wrapper function in the same php page:


function Logger($msg="undefined", $level=0) {
EDL_HTML_LOG($msg,$level,LOGFILE_HTML);
}

The LOGFILE_HTML can now be set as a define in the appliation.

However, this is still not satisfying since what if the user (uh..thats me) forgets to define the location of the Log file in of the applications.

Leave a Reply

Your email address will not be published. Required fields are marked *