Wednesday, October 17, 2012

A logger for PHP applications

     This is a simple logger implementation that you can plug into your php applications without installing anything.

     Logger class definition, comments are provided wherever necessary.

safeer@penguinpower:~/DEV/PHP$ cat logger.php
class logger {
### Variable declaration & initialization
private $logFile = NULL;
private $filePtr = NULL;
private $incScriptName = FALSE;
private $incScriptPath = FALSE;
### Constructor, sets log file name and log entry behaviour
function __construct($options) {
### Open logfile
if( isset($options['logfile'])) 
        { 
         $logDate = date('d-m-Y');
### Final logfile name should be <LOGFILE>.<DD-MM-YYYY>.log
         $this->logFile = $options['logfile'].".".$logDate.".log"; 
### Create if log file is not existing, then open for appending
         $this->filePtr = fopen($this->logFile,"a") 
                or exit("Unable to open logfile $file\n"); 
        }
### Abort if the logfile is not set during object creation
else 
        { exit( "Logfile should be defined\n" ) ; }
### Whether logger should add calling script name to the log file
### Include script name in log entry
if( $options['scriptname'] ==  TRUE )
        { $this->incScriptName = TRUE; }
### If set include full path of script, else just script name
elseif( $options['scriptpath'] == TRUE )
        { $this->incScriptPath = TRUE; }

}
### Destructor, close the file handle when object is destroyed
function __destruct() {
if($this->filePtr) { fclose($this->filePtr); }
}
### Logging happens here
### Each line in the log file ( log entry ) will start with a log prefix
### The log prefix will start with [DATE][LOG_TYPE]
### Log type will be one of INFO/DEBUG/WARN/CRIT
private function logme($logType,$logMsg) {
$timeStamp = date('Y-m-d H:i:s');
$logPrefix = "[".$timeStamp."]";
$logPrefix .= "[".$logType."]"; 
$message = NULL;
### Add script name to log prefix based on setting
if( $this->incScriptName == TRUE and $this->incScriptPath == TRUE )
        { $logPrefix .= "[".$_SERVER['PHP_SELF']."]"; }
elseif ( $this->incScriptName == TRUE and $this->incScriptPath == FALSE )
        {  $logPrefix .= "[".basename( $_SERVER['PHP_SELF'] )."]"; }
### Break down multi-line log message and append prefix to each line
foreach ( explode("\n",$logMsg) as $msg) {
        $message .= "$logPrefix $msg\n";
        }
### Write log entries to file
fwrite($this->filePtr, $message) 
or exit("Unable to write to log ".$this->logFile);

}
### Following functions are defined for the convenience of user
### All of them calls logme() funcation  internally

### Used to register informative messages
public function info($logMsg) {
$this->logme("INFO",$logMsg);
}
### Used to register debug messages
public function debug($logMsg) {
$this->logme("DEBUG",$logMsg);
}
### Used to register warning messages
public function warn($logMsg) {
$this->logme("WARN",$logMsg);
} 
### Used to register critical messages
public function crit($logMsg) {
$this->logme("CRIT",$logMsg);
}

}
?>


     Sample use of the logger

safeer@penguinpower:~/DEV/PHP$ cat logcaller.php
### Inlcude logger class definition
include_once("logger.php");
### Define
$opts['logfile']="/tmp/testLogger";
$opts['scriptname'] = TRUE;
$opts['scriptpath'] = FALSE;
$logger = new logger($opts);
### Register all types of log messages
$logger->info("Information Message");
$logger->debug("Debug Message");
$logger->warn("Warning Message");
$logger->crit("Critical Message");
?>



Run php application and see the logging.

safeer@penguinpower:~/DEV/PHP$ php logcaller.php
safeer@
penguinpower:~/DEV/PHP$ cat /tmp/testLogger.17-10-2012.log
[2012-10-10 13:31:54][INFO][logcaller.php] Information Message
[2012-10-10 13:31:54][DEBUG][logcaller.php] Debug Message
[2012-10-10 13:31:54][WARN][logcaller.php] Warning Message
[2012-10-10 13:31:54][CRIT][logcaller.php] Critical Message

No comments:

Post a Comment