Snipplet: PHP logging

I use this script often to debug my php applications & scripts where console output/ web browser output can’t be done (like debugging ajax signals).

This logging function has the following features:

  • Custom log location:
    define the relative path for your logfile. Make sure the path is writable for the webserver user (under ubuntu this is www-data)
  • Log levels:
    You can define from witch log level there should be logged.
  • App names:
    define witch section/function this log line is from


logger('ajaxPost->time',"Time is set at".$time); //Default loglevel 1
logger('ajaxPost->time',"Time is set at".$time,"2"); // loglevel 2
logger('ajaxPost->time',"Time is set at".$time,"3"); //loglevel 3, will not be logged because smaller than $logger['LEVEL'].


$logger['PATH'] = "/var/www/logs/master.".date('Ymd').".log";
$logger['LEVEL'] = 2;
function logger($name,$mesg,$level = 1){
	if (isset($_SESSION['username'])){
		$u ="[".$_SESSION['username']."]";
	} else  $u = "";
        global $logger;
	//echo $level;
	if ($level <= $logger['LEVEL']){
	        $line = date('M d Y H:i:s')." [".$name."]".$u.": ".$mesg."\n";
	               //Jan 07 2010 22:10:41 [MySection] : 
	        $f['fh'] = fopen($logger['PATH'],'a')or die("can't open file ".$logger['PATH']."!");


subutux wrote 34 posts

Post navigation

Leave a Reply