Advertisement

How To Tame Your PHP Error Logs

Posted on Thursday, October 22nd, 2009 at 10:00 pm

I recently watched a quick Screenr screencast by Jeffrey Way about logging your errors in PHP to a text file. Needless to say, I was a little bit inspired.

It was only a quick 5 minute tutorial so it didn’t go into much detail and after implementing it into one of my projects it needed some tweaking.

The main problem was there was the potential for your site to create thousands of indistinguishable error logs. My solution was to create folders to house daily log files. This makes your error logs live inside a nice folder structure broken down by year, month and day.

This was a quick script that I threw together so if you have any improvements please leave a comment and lets try and make this a bulletproof little function!

//log any php errors to a folder on the server
function log_errors(){

	$log_folder = MAIN_PATH . '/_logs';
	$file = null;
	$current_folder = null;

	//we need to find out if a month folder has been created
	$year = date('Y');
	$month = date('m');
	$day = date('d');

	//set the current folder path to your/site/path/_logs/2009
	$current_folder = "$log_folder/$year";

	//create the year folder if it's not already created
	if(!is_dir($current_folder)){ mkdir($current_folder); }

	//month
	$current_folder .= "/$month";
	if(!is_dir($current_folder)){ mkdir($current_folder); }

	//day
	$current_folder .= "/$day";
	if(!is_dir($current_folder)){ mkdir($current_folder); }

	//set the file that we want to create
	$file = $current_folder . '/' . date('G:i:s') . '.txt';

	ini_set('display_errors', 1);
	ini_set('log_errors', 1);
	ini_set('error_log', $file);
	error_reporting(E_ALL);

}

Be sure to check out jeffrey’s site for more interesting articles!

UPDATE: Thanks to Ryan for pointing out that we should switch to minutes with leading zeros (i) instead of using (m) which would check for the month :P

Share these links, you kinda have to!
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Twitter