Last Updated: February 25, 2016
· 2upmedia

Quick and Dirty PHP Logging

If you ever have an issue on your server perhaps a production server, you don't have a great logger package, and you just need to debug something quickly here's a trick.


$collection = array( 'item1', 'item2', 'item3');

$homepageGroup = Group::veryImportantCall( 'someparameter' );

error_log( "\n".var_export( compact( 'collection', 'homepageGroup'), true ) );

Output to the system logger

[03-Apr-2014 22:17:26 UTC] 
array (
  'collection' => 
  array (
    0 => 'item1',
    1 => 'item2',
    2 => 'item3',
  'homepageGroup' => NULL,

Since var_export() can return any variable as a string (except recursive objects) by sending the second the parameter as true you could get a nicely formatted response in your logs. Combine that with compact() and you have a really nice way to debug variables. The compact() function will return a nice associate array of your variables, just send it an array with the names of the variables you want.

Wherever possible use a logger that auto-formats variables already. Better yet use xDebug or Zend Debugger to do remote debugging which allows you to inspect the variable's values without having to touch your production code.

Normally you shouldn't be touching live production code, but there's always those edge cases where something works on your local/staging server, but not in production.