Home > PHP, Snippets of Code > Append text into a rotating log with PHP

Append text into a rotating log with PHP

If you ever needed a log rotate function in PHP check out this small snippet of code. It is meant to append lines of text into a log file, but avoiding it to grow limitless. When it reaches 2 Mb in size, automatically the log file is renamed adding .old extension to its file name. This is very useful for fast growing debugging log files. You may customize it defining another threshold for rotation triggering, just changing the value 2*1024*1024 ( 2 Mbytes). This code does not use external system calls, but just filesystem php native functions, so it should work properly under Linux and/or Windows servers. I am developing on a WAMP server over Windows 7 OS and this code seems to work as expected:

// Appends lines to file and makes sure the file doesn't grow too much
function append_line_to_limited_text_file($text, $filename) {
	if (!file_exists($filename)) { touch($filename); chmod($filename, 0666); }
	if (filesize($filename) > 2*1024*1024) {
		$filename2 = "$filename.old";
		if (file_exists($filename2)) unlink($filename2);
		rename($filename, $filename2);
		touch($filename); chmod($filename,0666);
	}
	if (!is_writable($filename)) die("<p>\nCannot open log file ($filename)");
	if (!$handle = fopen($filename, 'a')) die("<p>\nCannot open file ($filename)");
	if (fwrite($handle, $text) === FALSE) die("<p>\nCannot write to file ($filename)");
	fclose($handle);
}
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: