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 -

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 );
    }
}

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:

$data = array(
  'name' => 'Joseph',
  'url' => 'http://josephscott.org/'
);

debug_log( $data );

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

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

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

Related posts:

  1. PHP Helpers: html_print_r
  2. PHP Helpers: html_var_dump
  3. I Don’t Like PHP’s extract() Function
  4. PHP Helpers: esc_html
  5. PHP Helpers: redirect_url

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>