PHP: Error Logging

Here's a little bit of code I put together to handle error logging in PHP.

First, I set a couple variables for global use. I put these at the top of a common include file, or some other page that will be included anywhere the function might be called:

$g_Logging = true;  //  sets whether or not error logging is on
$g_LogLoc = "/var/www/site/error.log";  // default log file location

"$g_Logging" enables me to turn logging on and off globally. This is particularly important if you'll need logging during the build out stage, but not during production, where the output might not be monitored (and might eat up the disk).

"$g_LogLoc" is just where you want it to go.

This is the function, itself:

/*
  Writes a time-stamped message to a log
*/

function writeLog ($sMsg, $sAltLoc)
{
  global $g_Logging;
  global $g_LogLoc;
  if($g_Logging){
  $timeStamp = date("Ymd H:i:s");
  if (strlen(trim($sAltLoc)) == 0){$errorFile = $g_LogLoc;}
  if (strlen(trim($errorFile)) == 0) {$errorFile = getcwd(). "/err.log";}
  $errorMsg = $timeStamp . " " . $sMsg . chr(13) . chr(10);
        $fp = fopen($errorFile, 'a+');
        if(!$fp) {
                trigger_error('file_put_contents cannot write in file.', E_USER_ERROR);
            return;
         }
         fputs($fp, $errorMsg);
         fclose($fp);
  }
}

This will write the log to you default location, "$g_LogLoc", unless you send it a different location with the option varialbe "$sAltLoc". If neither are set, it will write the error log to the only location it knows for sure exists: it's own.

All lines are appended to the end of the log, although you can change that by modifying the options on "fopen".

To call it, do something like this:

if ($errMsg = tryTo($doSomething))
{
  // success.  do your thing.
}
  else
{
  // failure.  log it.
  $sMsg = "Warning:  Unable to do my thing - " . $errMsg;
  writeLog ($sMsg)
}
Tags: