Now that we've completed the design considerations, let's see how we can implement trace logs for an application. PHP provides a native function to log necessary information: error_log, but it is very basic and lacks a few of the basic design features we discussed above. What we will do is write our MyLog class using the Pear Log. Writing our own class will give us the flexibility to append and prepend strings to the log message centrally. The MyLog class's definition looks like this: *********************** MyLog.php*************************** <?php /** * MyLog -> This class is subclass of pear::log */
require_once 'Log.php' ; // pear Log class
class MyLog {
var $logger = Null ; // Log class singleton instance
function MyLog() // constructor { global $myGlobal ; $conf = array('mode' => 0600, 'timeFormat' => '%X %x'); $this->logger = &Log::singleton('file', $myGlobal['log']['logfile'], '', $conf, $myGlobal['log']['level']);
} // end of function MyLog
/** * @desc logs to the specified file * @param * below are the valid levels , always use nos for specifying log levels
0 System is unusable 1 Immediate action required 2 Critical conditions 3 Error conditions 4 Warning conditions 5 Normal but significant 6 Informational 7 Debug-level messages
*/
function writelog($logmsg, $priority=7, $file_name = "" , $line_no = "") { global $myGlobal ;
// Check the current file size
// we have two log files -> trace.last.log ang trace.log // both of these should not be greater than specified size limit // suppose specified size limit is 100 MB // in this case if trace.log (current log file) increases more than 50 MB // trace.last.log is deleted , trace.log is renamed to trace.log.last and // a new trace.log is created for logging
$lsize = filesize ( $myGlobal['log']['logfile'] ) ; // in bytes $fsize = $lsize/2 ;
if ($lsize >= $myGlobal['log']['size'] *1024*1024/2){ // exceeded the limit // delete if there's already some old file like .last unlink($myGlobal['log']['logfile']."last") ; // rename the current log file to filenaame.last.log rename($myGlobal['log']['logfile'], $myGlobal['log']['logfile'].".last") ;
}
// prepend the log message with unix timestamp $logmsg = mktime()." ".$logmsg ;
// append file name and line no $logmsg .= " ".$file_name ; $logmsg .= " ".$line_no ;
//append user login $logmsg .= " ".$_SESSION[current_login_id] ;
$this->logger->log($logmsg, $priority) ;
// mail logs if required if ($priority <= $myGlobal['log']['email_level'] ){
// send email $this->sendemail($logmsg, $priority) ;
}
}
function sendemail($logmsg, $priority) // implementation for sending notification through mail { // implement yourself }
/** * Destructor */ function _MyLog() { if ($this->_opened) { $this->close(); } } }
?>
blog comments powered by Disqus |
|
|
|
|
|
|
|