Easy to use logging for PHP

flattr this!

Hi,

I wrote this logging class for PHP which I thought of sharing. I have taken it directly from my project, so its not adapted for overall usage.

The class:

<?php
/**
 * Logging class
 *
 * Requires the define "logdir" to be set to an available path
 *
 * @author Paul Peelen <Paul@PaulPeelen.com>
 * @since 02 feb 2010
 */
class log
{
 private $sLogDir;

 function log()
 {
 $this->sLogDir = logdir . "/";
 }

 function db($sQuery)
 {
 // Check for the file
 $this->checkFile('db.log');

 $this->addToLog('db.log', $sQuery);
 }

 function debug($sText) {
 if(log_debug) {
 // Check for the file
 $this->checkFile('debug.log');

 if(is_array($sText)) {
 foreach($sText as $name => $value) {
 $this->addToLog('debug.log', "[$name] {");

 if(is_array($value)) {
 $this->debug($value);
 }
 else {
 $this->addToLog('debug.log', "\t$value");
 }

 $this->addToLog('debug.log', "}");
 }
 }
 else {
 $this->addToLog('debug.log', $sText);
 }
 }
 }

 function error($sText) {
 // Check for the file
 $this->checkFile('error.log');

 if(is_array($sText)) {
 foreach($sText as $name => $value) {
 $this->addToLog('error.log', "[$name] {");

 if(is_array($value)) {
 $this->debug($value);
 }
 else {
 $this->addToLog('error.log', "\t$value");
 }

 $this->addToLog('error.log', "}");
 }
 }
 else {
 $this->addToLog('error.log', $sText);
 }
 }

 function checkFile($sFile)
 {
 if(!file_exists($this->sLogDir . $sFile))
 {
 $file    = fopen($this->sLogDir . $sFile, "w+");
 fclose($file);
 return true;
 }
 else
 {
 return true;
 }
 }

 function addToLog($sFile, $sString, $bAddDate = true, $bAddNewLine = true)
 {
 $rFile     = fopen($this->sLogDir . $sFile, "a");
 $iIp    = getenv('REMOTE_ADDR');

 $sAddString    = "";

 if($bAddDate == true) $sAddString .= date("[Y-m-d H:i:s]") . "\t";
 $sAddString    .= "[$iIp]\t";
 $sAddString .= $sString;

 if($bAddNewLine == true) $sAddString .= "\n";

 fwrite($rFile, $sAddString);
 fclose($rFile);
 }
}

?>

class.log.php


Leave a Reply