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.